JavaScript和'this'在立即执行的函数内部

JavaScript and 'this' inside immediately executed functions

本文关键字:执行 函数 内部 this JavaScript      更新时间:2023-09-26

我一直在阅读JavaScript中"this"的复杂性。给定以下代码:

$(document).ready(function() {
    console.dir(this);
    (function foo() {
        console.dir(this);
    })();
});

在Chrome中,控制台显示第一个'this'作为'HTMLDocument'(如我所料),但第二个'this'是'undefined'。有人能给我一个好的解释吗?

调用javascript函数的方式改变了其中this的含义。在这里,您调用了一个没有与任何对象关联的方法,因此它没有要绑定的this值。

在第一种情况下,回调是通过JQuery调用,他们正在操纵回调,使this指向document DOM元素。很容易将其可视化为使用apply

调用回调。
yourCallback.apply(document, null);

你可以像这样修复第二个版本

$(document).ready(function() {
    console.dir(this);
    var that = this;
    (function foo() {
        console.dir(that);
    })();
});

或者用apply

$(document).ready(function() {
    console.dir(this);
    (function foo() {
        console.dir(this);
    }).apply(this, null);
});

this是当前函数被调用的上下文。

  • 当使用object.method()语法调用函数时,object成为上下文。
  • 使用function()语法调用函数时,没有上下文:它是空的。
jQuery以document作为上下文调用ready函数。你调用你的立即执行的函数没有上下文,这就是为什么它是空的。

你可以这样做:

// assign `this` to that so you can access `this` through `that`
var that = this; 
(function foo() {
    console.log(that);
}());

或:

// bind the function to `this` and then call it
$.proxy(function() { 
    console.log(this);
}, this)();

参见jQuery.proxy

或者

// call the function with `this` as context
(function() { 
    console.log(this);
}).call(this);

参见Function.call

如果将该代码放入加载了jQuery的页面控制台,则第二个"this"是DOMWindow,它是全局的"this"。不是 undefined

你的页面上一定有别的东西

第二个this在一个没有上下文的匿名函数中。this始终是函数级别的隐式变量,因此您的内部函数this遮蔽了外部this