我知道函数的范围应在定义后确定。
因此,据我了解,function(toy)
的范围应该是forEach
的范围,因此this
应该真的只是forEach
吗?但事实证明这是全球范围的。不知道为什么
function Cat(name) {
this.name = name;
this.toys = ['string', 'ball', 'balloon'];
};
Cat.prototype.play = function meow() {
this.toys.forEach(function(toy) {
console.log(this);
});
};
const garfield = new Cat('garfield');
garfield.play();
答案 0 :(得分:2)
正如其他人指出的那样,使用function
关键字声明的函数将具有自己的this
,并且取决于函数的调用方式,而不是其定义的上下文。正在使用.forEach()
(并且似乎倾向于es5语法),在this
方法内更改forEach()
的一种可能方法是使用thisArg,在这里您可以明确说明您的回调函数中应该包含this
:
function Cat(name) {
this.name = name;
this.toys = ['string', 'ball', 'balloon'];
};
Cat.prototype.play = function meow() {
this.toys.forEach(function(toy) {
console.log(this);
}, this);
// ^--- specify the thisArg
};
const garfield = new Cat('garfield');
garfield.play();
答案 1 :(得分:1)
使用ES5语法声明function()时,它不了解词法范围,因此this
已绑定到默认窗口。
这与您声明一个命名的全局函数然后通过引用将其传递完全相同。唯一的区别是您以内联方式声明了代码。
.prototype链上声明的函数自动绑定到其父对象。
如果您使用新的ES6语法() => {}
,则this
将绑定到当前词法范围。