1
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?

Tony54
  • 265
  • 1
  • 4
  • 9

1 Answers1

6

In this example this keyword points to the containing object "c"

No, it doesn't. this doesn't point anywhere until the function is called and its value depends on how it was called, not on where it was defined.

Here we can see that this still points to the c object as c.log() returns Object {name: "Updated c object", log: function}

It points to c because you called c.log(). It was called in the context of c.

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.

You are calling setname('Updated again! The c object');. There is no context (nothing_here.setname), there is no new keyword, there is no call or apply method and you are not in strict mode. Therefore it is called in the context of the default object which, in a browser context, is window.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335