Manpreet Krishan Manpreet Krishan - 3 years ago 129
Javascript Question

Weird behaviour of console.log() in an object

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

Answer Source

You create a foo object, and you assign it two properties:

  • You set a be a function with the text function(){console.log(this)}
  • You set bto 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download