I have a small question in JavaScript.
Here is a declaration:
function answerToLifeUniverseAndEverything() {
return 42;
}
var myLife = answerToLifeUniverseAndEverything();
If I do console.log(myLife), it will print 42, as I am just invoking the same instance of function resulting in 42 as the answer. (Basic rule on JavaScript that only references of objects are passed and not the object.)
Now, on the other, hand if I do:
var myLife = new answerToLifeUniverseAndEverything();
then I can’t invoke the function; instead, myLife becomes just an object? I understand that this is a new copy of the same function object and not a reference, but why can’t I invoke the method?
Can you please clarify the basic fundamental I am missing here?
By prefixing the call to
answerToLifeUniverseAndEverything()withnewyou are telling JavaScript to invoke the function as a constructor function, similar (internally) to this:JavaScript proceeds to initialize the
thisvariable inside the constructor function to point to a new instance ofanswerToLifeUniverseAndEverything. Unless you return a differentObjectyourself, this new instance will get returned, whether you like it or not.