Last active
April 8, 2016 14:42
-
-
Save xie-qianyue/96cb423eb61d3d6cbe5b63370cfda06d to your computer and use it in GitHub Desktop.
Binding this in callback
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 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(); |
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
// 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(); |
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 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(); |
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 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