I tried the following example but the 2 types console is returning 2 different results. I expected my custom object to be returned on both occasions, but result seems a bit strange. Can someone explain the outcome?
<html>
<head> </head>
<body>
<script>
var obj1 = {
printThis: function() {
console.log(this);
}
};
obj1.printThis(); //refers to my custom object
var func1 = obj1.printThis;
func1(); //refers to window object
</script>
</body>
</html>
Result:
While the first console returns Custom Object, 2nd returns the Window Object (though at StackOverflow due to their own anonymous function wrapper some other object it may refer to). But, in Chrome the 2nd console provides reference to the Window Object.
The output is different because of the context or environment in which the function (printThis
) is executing.
In first case, function's execution context is inside of obj1
. But in the second case, function is executing in the global context or environment.
If you want to execute the second function call to be executed inside obj1
, you have to bind it explicitly like: obj1.printThis.bind(obj1)
.
var obj1 = {
printThis: function() {
console.log(this);
}
};
obj1.printThis();
var func1 = obj1.printThis.bind(obj1);
func1();