Why does ‘this’ point to the global obj in this code:
function display(){
console.log(this); // 'this' will point to the global object
}
display();
But to the local object in this code:
var obj = {
name: 'Saurabh',
display: function(){
console.log(this.name); // 'this' points to obj
}
};
obj.display(); // Saurabh
Also what is a context object?
Thanks,
Andrej
This guy does a pretty good job of explaining it:
1 Like
This:
function display () {
console.log(this);
}
Is basically this:
globalThis.display = function () {
console.log(this.name);
};
So if you compare the other function:
var obj = {
name: 'Saurabh',
display: function () {
console.log(this.name);
},
};
this
, the calling context, is the object to the left of the dot. obj.display
– obj
is to the left of the dot. globalThis.display
– globalThis
is to the left of the dot.
In the first example, the calling context is the object globalThis
, which will, in a browser, normally (but not always) be an object called window
.
In the second example, it’s an object called obj
.
So when the code calls console.log
, first example tries to resolve globalThis.name
, second one tries to resolve obj.name
.
1 Like