Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save csdear/0d995c66e89b8c7b48b4 to your computer and use it in GitHub Desktop.
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.
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