Skip to content Skip to sidebar Skip to footer

What Version Of Javascript Introduced Arbitrary Constructor Return?

Someone in the question Is there any reason to manually return in a constructor function mentioned that he thought that returning arbitrary objects in constructor calls may have be

Solution 1:

If you look in ECMA-262 ed 1 (which is still available online from the ECMA site) you will see:

11.2.2 The new operator

The production NewExpression : new NewExpression is evaluated as follows:

  1. Evaluate NewExpression.
  2. Call GetValue(Result(1)).
  3. If Type(Result(2)) is not Object, generate a runtime error.
  4. If Result(2) does not implement the internal [[Construct]] method, generate a runtime error.
  5. Call the [[Construct]] method on Result(2), providing no arguments (that is, an empty list of arguments).
  6. If Type(Result(5)) is not Object, generate a runtime error.
  7. Return Result(5).

And then in §15.3.2.1 #18 the [[Construct]] method is explained (in the following, F is a newly constructed Function object):

18. Set the [[Construct]] property of F to a method that, when it is invoked, constructs a new object whose [[Prototype]] property is equal to the value of F.prototype at the time the [[Construct]] method is invoked (but if this value is not an object then the value of Object.prototype is used), then invokes F as a function (using its [[Call]] property) with the new object as the this value and the arguments given to the [[Construct]] method as the arguments. If the result of invoking the [[Call]] method is an object, that object becomes the result of the invocation of the [[Construct]] method; otherwise the new object becomes the result of the invocation of the [[Construct]] method.

So a constructor returning this by default has been in ECMAScript since the beginning.

Solution 2:

There are several reasons to return manually in the constructor function. Singleton is just one of them.

Constructors are just functions that are meant to be used with the new operator. When invoked in such a way, this would get bound to a an object that is created based on that function's prototype. That this is also the one that is returned when you invoke that function using new (or is bound to window if you don't use new).

this is a slight simplification of the process, but that should give a good overview

When you explicitly return an Object from such a constructor function - the original object that was created using that function's prototype is discarded and the explicit one is returned (as one would expect).

As far as I know it was always like this - or at least for as long as functions were allowed to return a value. :)

Here is a link:

From ECMA-262 3rd edition LS-like(1999 - so yeah, almost forever:)

Post a Comment for "What Version Of Javascript Introduced Arbitrary Constructor Return?"