Is a constructor always an object of a function?

I am reading the last link of ECMA-262, edition 5.1 of June 2011.

In section 8.6.2, table 9 relates to the internal [[Construct]] property:

Creates an object. Called using a new statement. SpecOp arguments are arguments passed to the new operator. Objects that implement this internal method are called constructors.

The standard does not say that a constructor must be a Function object. Can we have a constructor object that is not a function object?

Reference to standard on request

+6
source share
3 answers

While the term “constructor” is defined (as indicated by @RobG), there is nothing that would prevent the non-Constructor object from having [[Construct]] .

This is a bit confusing. This means that you can use the new operator on an object that is not Function (thus, it is not a "constructor" in accordance with 4.3.4 ), but does provide a [[Construct]] method.

Note that none of the standard objects are suitable for this, but host objects really can. A browser plugin, such as Java, can expose some object:

 new java.lang.String(); // it works, so java.lang.String has a [[Construct]] method java.lang.String instanceof Function // false Object.prototype.toString.call(java.lang.String).indexOf('Function') // -1 

Note that typeof java.lang.String returns "function" , although java.lang.String not a function. This is true in accordance with 11.4.3 (this is a host object with the [[Call]] method)

+3
source

The answer is very simple. ES5 § 4.3.4 says:

Constructor Function object that creates and initialises objects.

So, you have this, by definition, only a function can be a constructor. However, there are probably host objects that behave like constructors that do not have any other attributes of their own Function objects (for example, the original XMLHttpRequest object in IE that was implemented in ActiveX).

+4
source

Add an answer to Pumbaa80 (this is too long for a comment).

The confusion increases by 13.2.2 , according to which, when the construct function is executed, its call operation should be performed (but it does not say what to do when the construct object that is not a function is executed). Now the objects that implement call are function- invoked objects in accordance with 9.11 .

Also according to 4.2 "function is the called object". But of course, this does not mean that every called object is a function.

So, if I got this right, then not Function objects can have a construct method, as well as a call method. java.lang.String will be one such example.

0
source

Source: https://habr.com/ru/post/914603/


All Articles