回调函数的范围/ 这个

我理解函数的范围应该在定义时确定。


所以从我的理解来看,范围应该是范围,所以真的应该只是?但事实证明这是全球范围的。不知道为什么function(toy)forEachthisforEach


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();


慕后森
浏览 64回答 2
2回答

largeQ

正如其他人所指出的,使用关键字声明的函数将有自己的 ,并且取决于函数的调用方式,而不是定义它的上下文。由于您正在使用(并且似乎倾向于es5语法),因此更改内部方法的一种可能方法是使用thisArg,您可以在其中显式声明回调函数中应该包含的内容:functionthis.forEach()thisforEach()thisfunction 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();

狐的传说

当您使用 ES5 语法声明函数() 时,它无法识别词法范围,因此绑定到默认窗口。this这与声明命名的全局函数,然后通过引用传入它完全相同。唯一的区别是您以内联方式声明了代码。在 .prototype 链上声明的函数会自动绑定到其父对象。如果使用新的 ES6 语法,则将绑定到当前的词法范围。() => {}this
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript