这个内部嵌套函数

this inside nested function

本文关键字:函数 嵌套 内部      更新时间:2023-09-26

到目前为止,为了清楚理解,我认为总是指函数的所有者。

我主要考虑了三个案例。

    实例
  1. 方法,这是调用该方法的实例。
  2. 事件处理程序,元素是调用事件的函数的所有者。
  3. 全局命名空间中的函数,窗口是函数的所有者

但是当我创建一个内部函数并在那里调用该函数时会发生什么。即使在这种情况下,这也是指窗口。

function outer(){
    var inner = (function(){
        console.log(this);
    })
    inner();
}
outer();

谁能解释为什么这指的是简单的窗口。

您正在用 OO 术语思考,但您发布的代码不是 OO。正如 Rob W 在他的帖子中所说,默认this在严格模式下windowundefined

this仅在特定函数或情况上下文中为其提供值时更改值。

在类模拟中使用函数的地方,即实例化(通过new)而不是简单地调用,this如您所期望的那样指向实例。

function Dog(name) {
    this.name = name;
    alert(name);
}
var fido = new Dog('Fido'); //alerts 'Fido'

this提供上下文的其他情况包括事件处理程序(至少在addEventListener模型中,而不是较旧的 IE 中),以及任何时候使用 call()apply() 并自行手动设置this上下文。

另外,不要认为this指向JavaScript中的函数"owner"。在一个事件中,this指向受影响的元素,但将该元素视为"拥有"回调函数是没有帮助的 - 它只是在该元素的上下文中运行。

最后,正如昆汀所提到的,没有办法引用this的外部语境。您必须先将其缓存在变量中。

function Dog() {
    var that = this;
    setTimeout(function() {
        alert(this); //window - setTimeout() has overwritten the 'this' context
        alert(that); //we reference our cached, outer context
    }, 500);
}
var fido = new Dog('Fido');

this(在没有newbindcallapply或箭头函数魔术的情况下)是指调用函数的对象。

如果没有对象,则使用默认对象。对于 Web 浏览器,该对象是window的(严格模式下除外)。

// all comments apply to "inside the body of the bar function"
foo.bar();     // this is foo
foo.baz.bar(); // this is baz
bar();         // this is window

您可以将 this 的值复制到要调用的函数作用域中存在的另一个变量。

function outer(){
    var that = this;
    var inner = (function(){
        console.log(that);
    })
    inner();
}
outer();

。您可以使用各种方法更改this的值。

function outer(){
    var inner = (function(){
        console.log(this);
    })
    inner.apply(this);
}
outer();