Last active
August 29, 2015 14:27
-
-
Save dhigginbotham/73c977e82fa79dc96863 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this example shows how you can enforce | |
// context with bind, even if you use .call | |
// or .apply | |
var FirstExample = function(name) { | |
this.name = name; | |
this.sayName = function() { | |
return 'Hello ' + this.name + '!'; | |
} | |
this.shoutName = function() { | |
return 'Hey ' + this.name + '!!!!!!!'; | |
}.bind(this); | |
return this; | |
}; | |
var firstExample = new FirstExample('jon'); | |
// here we can easily override context | |
firstExample.sayName(); // Hello jon! | |
firstExample.sayName.call({name: 'dave'}); // Hello dave! | |
// now lets try to do it while yelling!!!!!!! | |
firstExample.shoutName(); // Hey jon!!!!!!! | |
firstExample.shoutName.call({name: 'dave'}); // Hey jon!!!!!!! | |
firstExample.shoutName.apply({name: 'mr miage'}); // Hey jon!!!!!!! | |
// second example | |
// this shows that not only can we bind | |
// one constructor to an object, but we can | |
// affect the parents output :) | |
var SecondExample1 = function() { | |
this.sayName = function() { | |
return 'Hello ' + this.name; | |
} | |
this.setName = function(name) { | |
this.name = name; | |
} | |
return this; | |
}; | |
var SecondExample2 = function() { | |
this.sayName = function() { | |
return 'Hello ' + this.name + '!!!!'; | |
} | |
this.setName = function(name) { | |
this.name = name; | |
} | |
this.sayStuff = function() { | |
return 'Stuff..'; | |
} | |
return this; | |
}; | |
var secondExample1 = new SecondExample1(); | |
secondExample1.setName('jon'); | |
secondExample1.sayName(); // Hello jon | |
var secondExample2 = SecondExample1.bind({})(); | |
secondExample2.setName('dave'); | |
secondExample2.sayName(); // Hello dave | |
var secondExample3 = SecondExample2.bind(secondExample1)(); | |
secondExample3.setName('shake'); | |
secondExample3.sayName(); // Hello shake!!!! | |
// whoa? | |
secondExample1.sayName(); // Hello shake!!!! | |
secondExample2.sayName(); // Hello dave | |
secondExample3.sayName(); // Hello shake!!!! | |
secondExample1.sayStuff(); // Stuff.. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment