在这些代码中,如何使用执行上下文来解释输出结果?

问题描述 投票:0回答:1
var obj={
            say: function(){
                console.log(obj); // undefined
            }()
        };

它最终输出undefined。我开始使用执行上下文的知识来解释它,但我对在上下文中创建方法时感到怀疑。

我知道在进入上下文后,我们首先进入创建阶段,并有一个包含变量和函数声明的变量对象。接下来我们进入执行阶段并完成varibale和function的赋值。在这个例子中,我们:

首先,进入全球执行上下文的创建阶段,objundefined。接下来,在创建阶段之后,我们进入执行阶段。代码开始执行,obj现在指向一个对象。但是,在上面的过程中,当创建say方法时?在全局执行或执行的创建阶段全球执行阶段?

(如果在创建阶段,那么全局执行上下文的变量对象应该是AO={ obj:undefined,say: referencce to <function>}

或者有没有更好的方法来解释为什么这里的结果是undefined?我在网上搜索过,看到有人说这是因为吊装。这是正确的吗?

javascript executioncontext
1个回答
1
投票

这是因为您在不指定obj值的情况下立即调用该函数。比较底部代码段中的两个场景:

var obj = {
  say: function() {
    console.log(obj); // Not undefined since it will run after obj is assigned
  }
};
obj.say();

var objUndef = {
  say: function() {
    console.log(objUndef); // undefined
  }() // <--- immediately calling
};
In your example you are not assigning a function, but rather the result of a function (because you call it immediately with ()), which is running before obj is even assigned. Thus the result is that you log undefined to the console instead of the obj value. If you first create the object and later call its say method using obj.say(), obj will be defined since you assign obj first before you attempt to call it.
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.