Globals Are Bad

JavaScript

// You can use 'this' in method definitions to refer to attributes of the
// method's object.

var obj = {
    name: 'foo',
    introduce: function() {
        alert('[1] - this.name is:'+this.name);
    }
};

obj.introduce();  //=> foo

// But 'this' does not follow the normal rules of scope in JavaScript. One
// might expect 'this' to be available with the same value via closure in the
// callback defined inside the method here.

var obj = {
    name: 'foo',
    introduce: function() {
        window.setTimeout(function() {
            alert(this);
            alert('[2] - timeout this.name is:'+this.name);
        }, 3000);
    }
};

obj.introduce(); //=> *pause* undefined

// In fact, this got bound to the global object in the callback. To get around
// this, assign the object reference to a regular variable that will have the
// same value inside the callback definition.

var obj = {
    name: 'foo',
    introduce: function() {
        var that = this;
        window.setTimeout(function() {
            console.log('timeout that.name is:', that.name);
        }, 3000);
    }
};

obj.introduce();  //=> *pause* foo

// This is true even of functions that were defined as a method.

var obj = {
    name: 'foo',
    introduce: function() {
        console.log('obj.introduce this.name is:', this.name);
    }
};

// When the function is invoked without 'obj.' in front of it, 'this' becomes
// the global namespace.

var introduce = obj.introduce;
introduce();  //=> undefined


// Method invocation and function invocation are two of the invocation patterns
// in JavaScript. A third is apply invocation, which gives us control over what
// 'this' will be assigned to during function execution.

introduce.apply(obj, null);  //=> foo