[英]Scope / this of callback function
I understand the scope of a function should be settled when it's defined.我了解 function 的 scope 应该在定义时解决。
so from my understanding, the scope of function(toy)
should be the scope of forEach
, so this
should really just be forEach
?所以据我了解,
function(toy)
的 scope 应该是forEach
的 scope ,所以this
真的应该只是forEach
吗? but it turns out to be global scope.但事实证明是全局 scope。 can't figure why
不知道为什么
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();
As pointed out by others, a function declared using the function
keyword will have its own this
, and depends on how the function is called, rather than the context that its defined in. Since you are using .forEach()
(and seem to be leaning towards es5 syntax), one possible way to change the this
inside the forEach()
method is to use the thisArg , where you can explicitly state what this
should be inside your callback function: As pointed out by others, a function declared using the
function
keyword will have its own this
, and depends on how the function is called, rather than the context that its defined in. Since you are using .forEach()
(and seem to be倾向于 es5 语法),在forEach()
方法中更改this
的一种可能方法是使用thisArg ,您可以在其中显式 state this
应该在回调 function 中:
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();
When you declare a function() using ES5 syntax, it has no awareness of lexical scope, thus this
is bound to the default window.当您使用 ES5 语法声明 function() 时,它不知道词法 scope,因此
this
绑定到默认的 window。
It's exactly the same as if you declared a named global function and then passed it in by reference.这与您声明一个命名的全局 function 然后通过引用传递它完全相同。 The only difference is that you declared the code inline.
唯一的区别是您声明了内联代码。
Functions declared on the.prototype chain get auto-bound to their parent object.在 .prototype 链上声明的函数会自动绑定到其父 object。
If you use the new ES6 syntax () => {}
then this
will get bound to the current lexical scope.如果您使用新的 ES6 语法
() => {}
,那么this
绑定到当前的词法 scope。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.