polkovnikov.ph
polkovnikov.ph

Reputation: 6632

Function-like classes in JavaScript

Is it possible to do new new A in JS with A !== Function? What's the desired structure of A then?

Upvotes: 2

Views: 97

Answers (2)

user663031
user663031

Reputation:

Yes, in theory.

function A() { 
  return function B() {
  } 
}
> new new A
  B {}

or

> new new A()
> new new A() ()

since the parentheses are optional with the new operator.

This takes advantage of the fact that a constructor may return something other than the constructed object. It is extremely unclear why anyone would ever want to do this. Also, this does not change the fact that new can only be invoked on a function.

Dept. of Curiosities

This

function A() { return A; }

allows you to do this

new new new new new new new new new new new new A

which there is no point whatsoever in doing.

Prototype Chains

You know that calling new on a constructor constructs an object with the prototype for that constructor. However, if you return any object other than this from a constructor, this, along with its associated prototype, is forever lost to the world. Whatever object you return has its own prototype, coming from wherever--not that of A. This applies equally to the case here where the constructor returns a function, in which case the relevant prototype is Function.prototype. Is there any way to arrange it, in the unlikely event that we cared, so that new A continues to return a functioning function, which we can do a new on, while also having access to A.prototype?

Not easily. If you want additional properties on the function B returned from new A, then you can just add those properties before returning function B.

Upvotes: 4

joews
joews

Reputation: 30330

No, it's not possible. A must be a function, regardless of its return value.

Source: ECMAScript 5 spec for the new operator:

If constructor does not implement the [[Construct]] internal method, throw a TypeError exception.

From the Function specification, we can see that [[Construct]] is a special internal (inaccessible) property of Function objects.

Upvotes: 0

Related Questions