Skip to content

Instantly share code, notes, and snippets.

@haishanh
Last active February 20, 2016 15:44
Show Gist options
  • Save haishanh/c32c8be3a21d1716a87d to your computer and use it in GitHub Desktop.
Save haishanh/c32c8be3a21d1716a87d to your computer and use it in GitHub Desktop.
understand javascript arrow function and this
/*!
* 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'
@haishanh
Copy link
Author

this script works natively in current Chrome release(V47).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment