【问题标题】:Detection of constructor (Symbol) - ES6构造函数(符号)的检测 - ES6
【发布时间】:2016-05-08 22:02:51
【问题描述】:

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

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

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

【问题讨论】:

  • 嗯,它是一个原生函数,那么你会如何处理“示例实现”?

标签: javascript constructor ecmascript-6 symbols


【解决方案1】:

为了与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

【讨论】:

    【解决方案2】:

    当一个函数作为构造函数被调用时,this 成为这个函数的原型。你可以检查它并抛出错误:

    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?,它有更多的细节和见解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2015-09-08
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      相关资源
      最近更新 更多