Caffeinated Simpleton » Blog Archive » An Introduction to JavaScript's "this" - 2 views
-
That’s what this is expected to be, anyway. It’s expected to be a reference to the current instance of whatever object it’s defined within.
-
It’ll give an error saying that this doesn’t have a member called condiments, even though it clearly does. What happened?!
- ...3 more annotations...
-
The setTimeout function, however, just has a reference to that function. When it calls it, it’s not aware of myHotDog, so JavaScript sets this to window
-
function HotDog() { var my = this; // my references the current this, which is correct. my.condiments = "mustard, ketchup"; my.getCondiments = function() { return my.condiments; //my is guaranteed to be a reference to the original "this" } }
-
In constructors, this is always your instance. So we created a new variable, my, that references the HotDog instance. This allows you to always refer to the HotDog instance, no matter how the getCondiments function is called.