Skip to content

Instantly share code, notes, and snippets.

@Cmdv
Last active September 13, 2015 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cmdv/eb71fd5cd93e46acf848 to your computer and use it in GitHub Desktop.
Save Cmdv/eb71fd5cd93e46acf848 to your computer and use it in GitHub Desktop.
// ---------- Default Binding ---------
//
function aFoo(){
console.log(this.aBar); // this is undefinied or global unless in strict mode
}
var aBar = "Default bar1";
aFoo(); // default binding rule
var a_o2 = {aBar: "Default bar2", aFoo: aFoo};
var a_o3 = {aBar: "Default bar3", aFoo: aFoo};
a_o2.aFoo(); a_o2.aFoo(); // implicit binding rule
a_o3.aFoo(); a_o2.aFoo(); // implicit binding rule
//
// ---------- Implicit Binding ---------
//
var b_o1 = {
bBar: "Implicit bar1",
bFoo: function(){
console.log(this.bBar);
}
};
var b_o2 = {bBar: "Implicit bar2", bFoo: b_o1.bFoo };
var bBar = "Implicit bar3";
var bFoo = b_o1.bFoo;
b_o1.bFoo(); // implicit binding rule
b_o2.bFoo(); // implicit binding rule
bFoo(); // default binding rule
// ---------- Explicit Binding ---------
//
function cFoo(){
console.log(this.cBar);
}
var cBar = "Explicit bar1";
var cObj = {cBar: "Explicit bar2"};
cFoo(); // default binding rule
cFoo.call(cObj); //Explicit Binding
// ---------- Hard Binding ---------
function bind(fn,o){ // .bind present in ES5
return function (){
fn.call(o);
};
}
function dFoo (){
console.log(this.dBar);
}
var dObj = {dBar: "Hard bar"};
var dObj2 = {dBar: "Hard bar2"};
dFoo = bind(dFoo,dObj);
dFoo();
dFoo.call(dObj2);
// ---------- NEW Binding ----------
// 1. brand new object created out of thin air
// 2. Object gets linked to
// 3. New oject gets bound with the this keyword
// 4. Will implicitly input a "return this" if no return
//
//
// ---------- Rules when callsite found ----------
//
// 1. Was the function called with 'new'? //New
// New keyword will override anything
//
// 2. Was it called with 'call' or 'apply' specifying an explicit 'this'? // Explicit Binding
//
// 3. Was the function called via a containing/owning object (context)? // Implicit Binding
//
// 4. Default: global object (exept strict mode becomes underfined) // Default binding
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment