Skip to content

Instantly share code, notes, and snippets.

@takahirohonda
Created February 10, 2020 03:47
Show Gist options
  • Save takahirohonda/7e4d30c13dc1d465db63f5d710574860 to your computer and use it in GitHub Desktop.
Save takahirohonda/7e4d30c13dc1d465db63f5d710574860 to your computer and use it in GitHub Desktop.
this-keyword-example.js
var a = 'global';
var check = {
a: 'hello',
b: function() {
console.log(this.a);
},
c: function() {
setTimeout(function(){
// this becomes global because setTimeout's call site is global
// as setTimout is window.setTimeout
console.log(this.a)
}, 0)
},
d: function() {
// we can reassign this to _this
var _this = this;
setTimeout(function() {
console.log(_this.a)
})
},
e: function() {
// Arrow function brings lexical scope
setTimeout(() => {
console.log(this.a)
})
}
}
check.b();
check.c();
check.d();
check.e();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment