[英]“this” refers to window when called inside a private function
I'm still wrapping my head around "this". 我仍然在围绕着“这个”。 Here I use "this" inside of a function
sayFoo
. 在这里,我在函数
sayFoo
使用“ this”。
I'm surprised that "this" is the window, when I log it from inside sayFoo(). 当我从sayFoo()内部登录时,“这是”窗口使我感到惊讶。
What am I not understanding here about context? 我在这里对上下文不了解什么?
myCoolThing = {
foo: "1",
doSomething: function() {
sayFoo();
function sayFoo() {
console.log(this.foo);
}
}
}
myCoolThing.doSomething(); // Errors with "foo" undefined
When you call sayFoo
, it is called without the object as the context. 当您调用
sayFoo
,将在没有对象作为上下文的情况下调用它。 Only functions which are properties of the object are called with the context as the parent object. 仅将作为对象属性的函数以上下文作为父对象调用。 This would work:
这将工作:
myCoolThing = {
foo: "1",
doSomething: function() {
sayFoo.call(this);
function sayFoo() {
console.log(this.foo);
}
}
}
More info on context . 有关上下文的更多信息 。
Function.prototype.call() simply calls the function with this
set to the first parameter it is called with (which, in this case, is the object since that is what this
is in a function which is a property of an object). Function.prototype.call()简单地调用与功能
this
集来被调用,(在这种情况下,是对象,因为这是第一个参数this
是一个函数,它是一个对象的属性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.