Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active December 27, 2017 10:46
Show Gist options
  • Save StevenJL/2a47227d99bd59587a8df6d343298e70 to your computer and use it in GitHub Desktop.
Save StevenJL/2a47227d99bd59587a8df6d343298e70 to your computer and use it in GitHub Desktop.
Arrow 2
// create a monkey constructor
function Monkey(favorite_food) {
this.favorite_food = favorite_food;
}
// set a method on the monkey constructor
Monkey.prototype.wait_and_ask = function() {
setTimeout(function () {
console.log('It has been 2 seconds, may I have a ' + this.favorite_food);
}, 2000);
}
var monkey = new Monkey('banana');
monkey.wait_and_ask() // It has been 2 seconds, may I have a undefined
/*
The reason it was undefined is because setTimeout is really a method
on the global object (ie. window.setTimeout) so "this" in setTimeout
refers to the global "this", which has an undefined "favorite_food".
We can fix this either with bind or the this vs that idiom.
*/
Monkey.prototype.wait_and_ask = function() {
setTimeout(function () {
console.log('It has been 2 seconds, may I have a ' + this.favorite_food);
}).bind(this), 2000);
}
// now the setTimeout function
// With ES6
Monkey.prototype.wait_and_ask = function() {
setTimeout(() => {
console.log('It has been 2 seconds, may I have a ' + this.favorite_food);},
2000
)
}
monkey.wait_and_ask() // It has been 2 seconds, may I have a banana
/*
The arrow function uses the scope of its containing context. So it is able
to access the this in the wait_and_ask method.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment