.call 方法在此关键字处抛出错误

.call method throws error at this keyword

在下面的简化代码中,我尝试将字符串 goblin 推入 creatures 数组。不幸的是,我在 this.push(x).
处遇到错误 Uncaught TypeError: Cannot read property 'push' of undefined at addName

如果 this 指向拥有它的对象,当它与 call 语句一起使用时,不应该是 creatures 对象吗?非常感谢您的帮助!

'use strict';
 
var creatures;
 
creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x) {
  this.push(x)
}

addName('goblin').call(creatures);

你需要像addName.call(creatures)一样打电话。在函数本身上调用 call 函数,而不是在其结果上调用,您已经这样做了。如果你的函数有参数,你可以在传递上下文后传递这些参数。

'use strict';
 
var creatures;
 
creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x) {
  this.push(x)
}

addName.call(creatures, 'goblin');

console.log(creatures);

你的代码有两个问题

  • undefined 上调用 call 方法 - 您正在对 [=14] 的 return 值调用 call 方法=] 方法调用 which returns undefined while call 只能在 function.
  • 上调用
  • call 方法将 this 参数作为第一个参数, 个参数作为函数 的参数,从 第二个参数开始调用.

你需要传递goblin作为call的第二个参数

 addName.call(creatures, 'goblin');

类 我相信在这种情况下套房更好

    'use strict';

class Creatures5{
    constructor(){
        this.creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];
    }   


    addName(x) {
      this.creatures.push(x)
        console.log(this.creatures)
    }
}
var CreatureObj = new Creatures5;
CreatureObj.addName('goblin');

或者你可以

'use strict';
var creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x){
    creatures.push(x)
}


this.addName.call('goblin')