Reputation: 357
var foo = {
a : function(){
console.log(this)
},
b : console.log(this)
}
foo.a()
Output :-
{}
{ a: [Function: a], b: undefined }
foo
variable is first declared and hence the key b
is evaluated, giving us the global object through console.log()
:- It displays {}
in node and Window
in browser
However, when foo.a()
is called, b
shows undefined
Am I missing some concept? Why isn't it evaluated again?
Thank you
Upvotes: 0
Views: 131
Reputation: 85161
You create a foo object, and you assign it two properties:
a
be a function with the text function(){console.log(this)}
b
to be the return value from console.log(this)
. console.log(this) gets executed immediately, and logs out the object. The object hasn't been given its properties yet, so it logs out {}
. The return value of console.log() is undefined
, so b
gets set to undefined
.You've now initialized your object, with a = some function and b = undefined. Later, when you call a, it logs out the foo object, with a = some function, and b = undefined.
Upvotes: 1