Objects, Functions And 'this'

'this' is immediately available, when we do console.log(this), 
we get: the window object from the Global Execution Context

Example 1:

function a() {
    console.log(this);
}

a(); - We also get the window object 

Note: 'this' points to the same address, location, at the Global Object 

Example 2: 

var c = {
    name: 'the c object',
    log: function (){
        console.log(this);
    }
}

c.log(); 

Everytime a function is invoke, a new Execution Context is created and
Javascript script decide what the keyword this should be pointing to. 
In the other cases, it was the window object, but in this case,
its a method on an object and that means we get: {name: "the c object", log: function}

In the case where a function is actually a method attached to an object, the 'this' keyword 
becomes the object that that method is sitting inside of. So when we see the 'this' keyword, 
its pointing at var c, the object that contains:

Object {
    name: "The c object", 
    log: function (){
        name : "the c object"
    }
}

Example 3 (People thinks is a bug in Javascript): 
When we have internal functions within a object, when its execution context is created, 
the 'this' refers to the Global Object

var c = {
    name: 'the c object',
    log: function (){
        this.name = 'Updated c object'
        console.log(this); 
        var setname = function(newname){
            this.name = newname; 
            //The name gets added to the Global Object even 
            //though it is sitting in the object it was created 
        }
        setname('Updated again' The c object)
        console.log(this);
    }
}

To fix example 3: 

var c = {
    name: 'the c object',
    log: function (){
        var self = this;

        self.name = 'Updated c object'
        console.log(this);

        var setname = function(newname){
            self.name = newname; 
        }

        setname('Updated again' The c object)
        console.log(self);

    }
}

Note:

Summary: When 'this' is called in a function, will link to the Global Object, 
when the function is a method on an object, the 'this' points to the object. 
However internal function has a problem, so we need to do the self = this.

results matching ""

    No results matching ""