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

问题描述

var obj={
            say: function(){
                console.log(obj); // undefined
            }()
        };

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

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

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

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

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

标签: javascriptexecutioncontext

解决方案


It is because you are immediately calling the function without assigning the value of obj. Compare the two scenarios in the bottom snippet:

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.


推荐阅读