Reputation: 32
var obj = {};
obj.fn = function() {
return this;
}
output: Window object
is the 'this' not pertaning to 'obj' which is the objectof property 'fn'?
but if I make declare like this below...
var obj = {
fn: function() {
console.log(this);
}
}
output is... Object object
are they not the same?
Upvotes: 0
Views: 60
Reputation: 11112
Both your examples shall return the object itself with the console log of this
, the window object is logged when reading this
in the global scope:
var obj = {};
obj.fn = function() {
console.log(this);
}
// logs window
console.log(this);
// logs object
obj.fn();
var obj1 = {
fn: function() {
console.log(this);
}
}
// logs object
obj1.fn();
this
will always take the value of the containing scope
Upvotes: 3