总结立即执行函数的this

701 阅读1分钟

立即执行函数

在浏览器环境中,立即执行函数不管是在全局定义还是在函数内定义,其this都指向window;在nodejs环境中结果又会不一样。

  • 在全局中定义立即执行函数
var name = "Tom";
(function () {
    //其中this.name指向window的Tom,所以this.name并不为undefined
    if (typeof this.name == "undefined") {
        var name = "Jack";
        console.log("Goodbye" + this.name);
    } else {
        console.log("Hello" + this.name);
    }
})();//最终输出 HelloTom//将this.name更改为name
var name = "Tom";
(function () {
    //在立即执行函数内部并没有定义name,故这里的name是undefined
    if (typeof name == "undefined") {
        var name = "Jack";
        console.log("Goodbye" + name);//输出Goodbye Jack
    } else {
        console.log("Hello" + name);
    }
})();
  • 在函数中定义立即执行函数
var name = "Jarry"
function foo() {
  var name = "Tom";
  (function () {
    if (typeof this.name == "undefined") {
      var name = "Jack";
      console.log("Goodbye" + this.name);
    } else {
      console.log("Hello" + this.name);
    }
  })();
}
foo();//输出Hello Jarry

虽然立即执行函数定义在函数内部,但是其this始终指向window

var name = "Jarry";
var obj = {
  name: "张三",
  foo: function () {
    (function () {
      if (typeof this.name == "undefined") {
        var name = "Jack";
        console.log("Goodbye" + this.name);
      } else {
        console.log("Hello" + this.name);
      }
    })();
  },
};
obj.foo();

即使是通过对象调用,立即执行函数的this也执行window

总而言之,在浏览器环境中,不管立即执行函数定义在哪儿,其this始终指向window