2

I am checking out ES6 features and the Symbol type created a question for me.

With ES6 we cannot apply the new operator on Symbol(). When we do it, it throws an error. And it does this checking if the function is being used as constructor. So, how it does check if the function is being used as constructor or not behind the scenes? (Implementation might change depending on the platform.)

Could you share any example implementation?

Guido Domenici
  • 5,146
  • 2
  • 28
  • 38
serkan
  • 6,885
  • 4
  • 41
  • 49

2 Answers2

4

In order to be used with new, a Function object must have an internal [[Construct]] property. While ordinary user-defined functions do have it set automatically, this is not necessarily true for built-in ones:

new Symbol()   // nope
new Math.cos() // nope

ES6 arrows and methods don't have [[Construct]] either:

fn = (x) => alert(x);
new fn(); // nope

class Y {
  foo() {
  }
}

let y = new Y();
new y.foo(); // nope
georg
  • 211,518
  • 52
  • 313
  • 390
2

When a function is called as a constructor, this becomes a prototype of this function. You can check it and throw Error:

function NotConstructor() {
  if(this instanceof NotConstructor) {
    throw new Error('Attempt using function as constructor detected!')
  }
  console.log('ok');
}

NotConstructor();  // 'ok'
new NotConstructor(); // throws Error

Also, see a relevant question How to detect if a function is called as constructor?, it has more details and insights about it.

Community
  • 1
  • 1
just-boris
  • 9,468
  • 5
  • 48
  • 84