Javascript - Context

by Charlie Winfrey

JavaScript

// 1) 
// Default binding
//
// Behaves like a catch-all
// Will use the global object
// However in strict mode, it will be undefined

var a=1;

// "this" is the global object, window
console.log("Window is this:", (this === window)); // true
console.log("Window.a is a", (window.a === a)); // true

function foo() { // new scope
    console.log("This is window inside the function: ", this === window);
};

foo();

console.log("Function foo is on the window: ", foo === window.foo);

// 2) 
// Implicit Binding
//
// When inside an object method
// the context is the container object itself

var myObject = {
    sayHello: function () {
        console.log("Hi! My name is " + this.myName);
        
        // Warning: Inner function context is not the object
        function innerFunction() {
             console.log("Does inner have access to name?", this.myName);   
        }
        innerFunction();
        
    },
    myName: "Rebecca"
};

// myObject is the context for sayHello
myObject.sayHello();

// you can copy functions around
var newObject = {myName : "Jim"};
newObject.sayHello = myObject.sayHello;

// newObject is the context for sayHello when invoked here
newObject.sayHello();

// 3)
// Explicit Binding
// 
// All functions can have their context forced to something else
// using .call(), .apply()

console.group("Saying hello via call");
myObject.sayHello.call(newObject);
console.groupEnd();

// 4)
// Hard binding
//
// You can create a new function from an existing function
// and lock the binding to a specific context 

console.group("Saying hello via bind");

var boundSayHello = myObject.sayHello.bind(newObject);
boundSayHello();

console.groupEnd();


// 5)
// new Binding
//
// When a function is used as a Constructor with "new" keyword
// a new object is created and set as the context 
// for the constructor function
var MyConstructor = function(name) {
     this.name = name;   
}

var newObjectFromConstructor = new...