Okay, I stumbled upon this piece of code..
How come this works? What sort of evil scheme does JavaScript use to resolve variables?
The way I see it, as a C++ kind of guy: the class/object definition contains a non-existent reference to an object of the class being defined. Seriously, how?
(To be honest, I understand partially – I could deduce a strawman concept of how and when JS resolves names.. but maybe this way the question will be of more use to someone else, someday)
Guilty code:
function Sio() {
this.someValue = 5;
this.doStuff = function() {
console.log("look: "+howDoYouResolveThisYouFoulCreature.someValue);
};
}
var howDoYouResolveThisYouFoulCreature = new Sio();
That seems so wrong.
Lots of concepts here, and I’m not sure which one is giving you troubles…
The two most likely ones are
new/thisandvar.new/thisWhen you call a function the value of
thisis determined by the context in which you call it.If you use the
newkeyword, you create an instance of the function and make that instance the context.When you call
howDoYouResolveThisYouFoulCreature.doStuff()you are accessing that instance as a global. It would usually make more sense to:Since
foo.doStuff()makesfoothe context for that invokation ofdoStuff()(which makes the function reusable between different instances ofSio)varvar somethinganywhere inside a function will scope that variable to that functionvarstatement at the top of a function to avoid confusionAlso, the
doStufffunction is not called beforehowDoYouResolveThisYouFoulCreaturehas a value. Until that point all that matters is that the function is syntactically correct, it doesn’t matter what type the variable is.