Last active
February 20, 2016 15:44
-
-
Save haishanh/c32c8be3a21d1716a87d to your computer and use it in GitHub Desktop.
understand javascript arrow function and this
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
/*! | |
* understand `arrow function` and `this` | |
* see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions | |
*/ | |
var id = 'global'; | |
var o = { | |
id: 'o', | |
echoThisId() { | |
console.log(this.id); | |
}, | |
echoThisIdDelay() { | |
setTimeout(this.echoThisId, 1000); | |
}, | |
echoThisIdDelay2() { | |
setTimeout(function () { | |
this.echoThisId(); | |
}, 1000); | |
}, | |
echoThisIdDelay3() { | |
setTimeout(() => this.echoThisId(), 1000); | |
} | |
} | |
o.echoThisId() // 'o' | |
//o.echoThisIdDelay(); // 'global' | |
// o.echoThisIdDelay2(); // Uncaught TypeError: this.echoThisId is not a function | |
o.echoThisIdDelay3(); // 'o' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this script works natively in current Chrome release(V47).