Skip to content

Instantly share code, notes, and snippets.

@xie-qianyue
Last active April 8, 2016 14:42
Show Gist options
  • Save xie-qianyue/96cb423eb61d3d6cbe5b63370cfda06d to your computer and use it in GitHub Desktop.
Save xie-qianyue/96cb423eb61d3d6cbe5b63370cfda06d to your computer and use it in GitHub Desktop.
Binding this in callback
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
console.log(this.age); // 1 2 3 ...
}, 1000);
}
var p = new Person();
// example from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
console.log(this.age); // NaN
}, 1000);
}
var p = new Person();
function Person() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
console.log(self.age); // 1 2 3 ...
}, 1000);
}
var p = new Person();
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(growUp.bind(this), 1000);
function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
console.log(this.age); // 1 2 3 ...
}
}
var p = new Person();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment