new (getClass()) 是什么意思?

What‘s does new (getClass()) mean?

function getClass(name) {
   switch (name) {
      case 'string': return String;
      case 'array': return Array;
      default: return Object;
   }
}
obj = new (getClass());

谁能解释一下这些代码,我现在明白了,但是什么是 new()?

 obj = new (getClass());

这意味着:

  1. 调用不带参数的 getClass 函数 (getClass())。 return 要么是 String,要么是 Array,要么是 Object,在本例中是后者。

  2. getClass() 的 return 值上调用 new。在这种情况下,这等同于 new Object,它创建了一个新对象。

你可以使用

object = new getClass()(); // object = new (getClass());

这更好地解释了发生了什么。它调用函数 getClass 和 returns 一个新实例的对象。

function getClass(name) {
    switch (name) {
        case 'string': return String;
        case 'array': return Array;
        default: return Object;
    }
}

var typeObject = new getClass()(),
    typeArray = new getClass('array')(),
    typeString = new getClass('string')();

[typeObject, typeArray, typeString].forEach(function (o) {
    console.log(typeof o);
    if (typeof o === 'object') {
        console.log('hasOwnProperty' in o);
        console.log('splice' in o);
    }
});
.as-console-wrapper { max-height: 100% !important; top: 0; }