0

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?

2
  • I'm not sure how you would get an error from that line, what's the syntax for you foo function then? Unless foo is an object. Commented Jun 9, 2014 at 9:47
  • @MackieeE Can we write a function that is not a constructor? Commented Jun 9, 2014 at 9:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1: Not sure why the -1, this seems to be correct to me. OP asked for any function without constructor – there you have it.
4

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.

Comments

1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.