Skip to content Skip to sidebar Skip to footer

Invoking A Function Object In Javascript

I have a small question in JavaScript. Here is a declaration: function answerToLifeUniverseAndEverything() { return 42; } var myLife = answerToLifeUniverseAndEverything(); If

Solution 1:

By prefixing the call to answerToLifeUniverseAndEverything() with new you are telling JavaScript to invoke the function as a constructor function, similar (internally) to this:

var newInstance = {};
var obj = answerToLifeUniverseAndEverything.call(newInstance); // returs 42if (typeof obj === 'object') {
  return obj
} else {
  return newInstance;
}

JavaScript proceeds to initialize the this variable inside the constructor function to point to a new instance of answerToLifeUniverseAndEverything. Unless you return a different Object yourself, this new instance will get returned, whether you like it or not.

Solution 2:

When you do var myLife = answerToLifeUniverseAndEverything();, myLife is simply holding the return value from the function call - in this case, 42. myLife knows nothing about your function in that case, because the function was already called, returned, and then it assigned the resulting value (42) to the new variable myLife.

A completely different thing happens when you do var myLife = new answerToLifeUniverseAndEverything(); - instead, a new object is created, passed to the function as this, and then (assuming the function doesn't return an object itself), stored in the newly created variable. Since your function returns a number, not an object, the newly generated object is stored.

Solution 3:

Try:

function answerToLifeUniverseAndEverything() {
  return42;
}

var myLife = answerToLifeUniverseAndEverything;

alert(myLife());

When you do:

var myLife = answerToLifeUniverseAndEverything();

you're assigning the function result to myLife ie 42.

Solution 4:

I think i've described the behaviour of new elsewhere. Basically when you do new f() the JS engine creates an object and passes that as this, then uses that object if the return value of f() is not an object.

eg.

o = new f();

is equivalent (approximately) to

temp = {};temp2 = f.call(temp);o = typeof temp2 === "object" ? temp2 : temp;

Solution 5:

If I do console.log(myLife) It'll print 42, as I am just invoking the same instance of function resulting in 42 as the answer. (Basic rule on javascripts that only references of objects are passed and not the object)

Not quite. This is because you're assigning the return value of answerToLifeUniverseAndEverything() to myLife. If you wanted to make a copy of the function, drop the brackets:

var myLife = answerToLifeUniverseAndEverything;
console.log(myLife());

Post a Comment for "Invoking A Function Object In Javascript"