var x = 3;
var obj1 = {
x:2,
obj2:{
x:1,
fun: function() {
console.log(this.x);
}
}
}
var exec = obj1.obj2.fun;
exec();
obj1.obj2.fun();
Why the above code returns 3
and 1
?
var x = 3;
var obj1 = {
x:2,
obj2:{
x:1,
fun: function() {
console.log(this.x);
}
}
}
var exec = obj1.obj2.fun;
exec();
obj1.obj2.fun();
Why the above code returns 3
and 1
?
when the exec()
function calls it refer the this
as window object. So that it is displaying 3 as output. Because the global x
variable has the value 3.
When the obj1.obj2.fun()
function calls it refer the this
is obj2 object. So that it is displaying 1 as output. Because obj2 has it is own property x with the value 1.
You can get more clarity about this
here. understand-javascripts-this-with-clarity-and-master-it
var exec = obj1.obj2.fun
This statement returns the reference of the function. Not the value that the function returns.
Now when you call exec(), it will run the function but will take the value of the global variable x.
so basically if you console.log exec, it will show you the function code, not the value.
In the last line, you are actually executing the function from within the object, so it returns the value of obj2.x.