Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 7)

Objects, Functions, and this

  • this can be changed depending on how the function is called
function a() {
    console.log(this);
}
a(); //-> window
  • When you create a function statement or expression, this still points to the global object if you are simply invoking the function
var b = function() {
    console.log(this);
}
b(); //-> window
  • Even though there are 3 execution contexts (global, a, b) and they all get their own this keyword, all the this keywords point to the same address in the computer's memory (the global object).
var c = {
    name: 'The c object', //property (primitive)
    log: function() { //method (function)
        console.log(this);
        }
}
c.log(); //-> 'The c object'

var c = {
    name: 'The c object',
    log: function() {
        var self = this;
        self.name = 'Updated c object';
        console.log(self);
        
        var setName = function(newName) {
            self.name = newName;
        }
        setName('Updated again! The c object');
        console.log(self);
    }
}
  • use var self = this at the beginning of the function.
  • self and this are both objects so they are going to be set by reference (each point to the same location in memory).
  • Change this to self everywhere inside the function to not get confused about which object you are pointing to.
  • self in the setName function follows the lexical chain to find the variable self which points to the whole The c object allowing mutation of that object rather than the global object.