var obj={
say: function(){
console.log(obj); // undefined
}()
};
It finally output undefined
.And I began to explain it using the knowledge of execution context,but I felt doubt about when the method is created in the context.
I know that after entering the context,we first enter the creation phase and have a variable object which includes the variable and function declarations.Next we enter the execute phase and finish the assignment of varibale and function.So in this example,we:
First,enter the creation phase of the global excution context,and the obj
is undefined
.
Next,after the creation phase,we enter the execute phase.The codes begin to excute and obj
now points to an object.However,in the process above,when the say
method is created?During the creation phase of global execution or the execute phase of the global execution?
(If during the creation phase,then the variable object of the global execution context should be AO={ obj:undefined,say: referencce to <function>}
)
Or is there any better way to explain why here the result is undefined
? I have searched online and saw someone say this is because hoisting.Is it correct?
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
};
()
), 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.