为什么 IIFE/函数不能访问“this"?在外部功能? [英] Why can't IIFE/function access "this" in outer function?

查看:34
本文介绍了为什么 IIFE/函数不能访问“this"?在外部功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

它在控制台打印:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

前两个很明显,但我不明白第三个和第四个,为什么 IIFE 可以访问 self 但没有访问权限?我认为它创建了一个闭包,因此它可以访问外部变量 self 和 this ?

The first two are pretty obvious, but I don't understand for the third and fourth one, why does the IIFE has access to self but doesn't have the access for this? I thought it creates a closure so it has access to the outer variables self and this ?

推荐答案

我不确定这是否能解决您的问题,但是您可以通过将 this 作为参数传递给 IIFE 来绑定它:

I'm not certain that this solves your problem, but you can bind this by passing it as an argument to the IIFE:

(function(context) {
    console.log("inner func:  context.foo = " + context.foo);
    console.log("inner func:  self.foo = " + self.foo);
}(this));

小提琴

这篇关于为什么 IIFE/函数不能访问“this"?在外部功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆