Saturday, May 24, 2014

Javascript This keyword

This is a variable that is available when you use functions, and depending on how the function was invoked This can be different things.


// This - will be global scope
function myFunction() {
    console.log('This is a lot of stuff:');
    console.log(this);
}

// This - will be the myThing object
var myThing = { name: 'john', age: 21};
myThing.doStuff = function(){
    console.log(this);
    console.log(this.name);
};

// This function outputs:
// { name: 'john', age: 21, doStuff: [Function] }
// john


(function doTheFunctions(){
    myFunction();
    myThing.doStuff();
})();

No comments:

Post a Comment