user2953119
user2953119

Reputation:

Constructor in JavaScript

Is there exist a function which is not a constructor in JavaScript. I.e. the following line will be cause TypeError:

var a= new foo(); //foo is not a constructor

In the other words I would like to know the following:

Is there exist a function that has no [[Construct]] internal property?

Upvotes: 0

Views: 149

Answers (3)

James Allardice
James Allardice

Reputation: 165941

Yes, it is possible for built-in functions to not implement the [[Construct]] property. The ES5 spec clearly states the following in the section on Standard Built-in ECMAScript Objects:

None of the built-in functions described in this clause that are not constructors shall implement the [[Construct]] internal method unless otherwise specified in the description of a particular function. None of the built-in functions described in this clause shall have a prototype property unless otherwise specified in the description of a particular function.

At first glance it doesn't appear that any of the functions subsequently listed actually state otherwise.

As demonstrated by Quentin it appears that a number of host objects implement functions without [[Construct]] properties too. If you want to achieve the same you'll have to settle for the solution provided by Ingo Bürk since there is no way to control whether or not the internal [[Construct]] property is set on any function object. The section of the spec that deals with Creating Function Objects includes the following step which is not optional and contains no conditions:

 7. Set the [[Construct]] internal property of F...

Upvotes: 1

Ingo Bürk
Ingo Bürk

Reputation: 20033

This is not technically writing a function without a constructor, but a similar effect:

function Foo() {
    if( this instanceof Foo ) {
        throw new TypeError( "Foo is not a constructor" );
    }

    console.log( "I was called as a function" );
}

var foo = new Foo(); // TypeError: Foo is not a constructor
Foo(); // I was called as a function

It really only is an old trick some people use to do the exact opposite: enforce that a function is called as a constructor. So the above just inverts that principle.

Upvotes: 4

Quentin
Quentin

Reputation: 943108

Yes, there is:

> new window.open()
TypeError: window.open is not a constructor

> new parseInt(123)
TypeError: parseInt is not a constructor

Some other built-in functions will probably give the same result.

Upvotes: 4

Related Questions