Created
July 18, 2014 14:08
-
-
Save CharlotteGore/0562e8cd42d1ad77da65 to your computer and use it in GitHub Desktop.
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 Tiger (){ | |
this.name = "Tiger King!"; | |
return this; | |
} | |
Tiger.prototype.waitABitThenRoarMyName = function (){ | |
setTimeout(function (){ | |
alert('Rawr!!! I AM ' + this.name); | |
}, 500); | |
} | |
var tiger = new Tiger(); | |
tiger.waitABitThenRoarMyName() // half a second goes by an 'Rawr!!! I AM undefined' pops up on the screen. | |
// the fuck?!!! | |
// well this is because when setTimeout calls that function which has 'alert' in it, 'this' points to | |
// the window, not our tiger. This is because setTimeout is actually window.setTimeout. This is also true | |
// for onclick handlers and lots of other asynchronous events. | |
// but.. it's pretty easy to work around this. Let's try this again.... | |
Tiger.prototype.waitABitThenRoarMyName = function (){ | |
// We make a new variable called _this, which points to our current tiger instance. | |
var _this = this; | |
setTimeout(function (){ | |
// here, 'this' points to the window. But '_this' still points to | |
// our tiger instance.. so this works! This is called a closure. It's | |
// one of the most powerful and useful bits of Javascript. | |
alert('Rawr!!! I AM ' + _this.name); | |
}, 500); | |
} | |
var tiger = new Tiger(); | |
tiger.waitABitThenRoarMyName() // half a second goes by an 'Rawr!!! I AM TIGER KING' pops up on the screen. | |
// hurrah, we have been successful. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment