var c = {
name: 'The c object',
log: function() {
console.log(this);
}
In this example this
keyword points to the containing object "c"
c.log()
returns Object {name: "The c object", log: function}
var c = {
name: 'The c object',
log: function() {
this.name = 'Updated c object';
console.log(this);
}
Here we can see that this still points to the c object as
c.log()
returns Object {name: "Updated c object", log: function}
However in the following code:
var c = {
name: 'The c object',
log: function() {
this.name = 'Updated c object';
console.log(this);
var setname = function(newname) {
this.name = newname;
}
setname('Updated again! The c object');
console.log(this);
}
}
If we type c.log()
, instead of setting the name to "Updated again! The c object", it created an object in window with that same property.
Specific question I have is: the first this
keyword is inside a function but doesn't point to the global object, why does the this
keyword in the setname
function point the global object?