简体   繁体   English

“ this”是指在私有函数中调用时的窗口

[英]“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.

相关问题 JavaScript 这是指 window 而不是 ZC1C425268E68385D1AB5074C17A94F1 内部的 object - JavaScript this refers to window instead of object inside function Javascript:为什么私有函数里面的“this”指的是全局范围? - Javascript: why “this” inside the private function refers to the global scope? 这是指javascript的内部函数 - this refers to inside function on javascript 为什么在调用apply()或call()时,“ this”指向函数内部的窗口? - Why 'this' points to window inside a function when apply() or call() is being called? sinon未检测到内部承诺中的私有功能 - sinon not detecting private function called inside promise 为什么在调用一个函数时首先将其作为父对象,而在随后的函数调用中却将此对象称为窗口对象? - Why when invoking a function is the first this the parent object, but on a subsequent function call this refers to the window object? 当函数本身没有在全局上定义时,为什么这个内部函数指的是节点中的全局对象? - why this inside function refers to global object in node when function itself is not defined on global? 在函数内部调用函数时的不同结果 - Different Result when function is called inside a function onclick调用的js函数中的window.location - window.location inside js function called by onclick 当在对象内部调用函数时,JavaScript会监听 - JavaScript listen for when a function is called inside an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM