Last active
August 29, 2015 14:12
-
-
Save csdear/0d995c66e89b8c7b48b4 to your computer and use it in GitHub Desktop.
this Keyword Correct Contexting Functions : Apply, Call and Bind call, apply and bind are ways to override the difficulties with the this keyword and context. bind doesn’t work well with legacy browsers, so if you are developing for IE8 etc, use the apply and call functions.
This file contains 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
function Car(type) { | |
this.type = type; | |
this.speed = 0; | |
this.func = function() { | |
return this.type; | |
} | |
} | |
var bmw = new Car("BMW"); | |
var func = bmw.func; | |
console.log(func.call(bmw)); // outputs BMW | |
console.log(func.apply(bmw)); // outputs BMW | |
// the bind function | |
function Car(type) | |
this.type = type; | |
this.speed = 0; | |
this.func = function() { | |
return this.type; | |
} | |
} | |
var bmw = new Car("BMW"); | |
var func = bmw.func.bind(bmw); | |
console.log(func()); // outputs BMW |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment