检测构造函数(Symbol)——ES6

Detection of constructor (Symbol) - ES6

我正在检查 ES6 功能,Symbol 类型为我创建了一个问题。

对于 ES6,我们不能在 Symbol() 上应用 new 运算符。当我们这样做时,它会抛出一个错误。它会检查函数是否被用作构造函数。那么,它如何检查该函数是否在幕后用作构造函数? (实施可能会因平台而异。)

你能分享任何示例实现吗?

为了与 new 一起使用,函数对象必须具有内部 [[Construct]] 属性。虽然普通的用户定义函数确实会自动设置它,但对于内置函数来说不一定如此:

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

ES6 箭头和方法也没有 [[Construct]]:

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

class Y {
  foo() {
  }
}

let y = new Y();
new y.foo(); // nope

当一个函数作为构造函数被调用时,this成为这个函数的原型。您可以检查它并抛出 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

另请参阅相关问题How to detect if a function is called as constructor?,其中有更多详细信息和见解。