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

So could anyone pls explain these codes, I understand new but what is new()?

Scandy
  • 23
  • 4
  • The parentheses don't do anything, they're just for grouping things. It seems to be the programmer's personal style or overcautiousness (there are unnecessary parentheses in the switch statement too.) – JJJ Feb 28 '17 at 12:11
  • 2
    @JJJ Wrong. The parentheses are necessary to ensure that `getClass` is called with no parameter, and then `new` is invoked on the result, such as `String`. Without the parentheses, it would invoke the `getClass` function itself as a constructor. –  Feb 28 '17 at 12:15
  • @torazaburo, would you like to answer the question? it would works with `obj = new getClass()();` as well, which is more obvious than the other style. – Nina Scholz Feb 28 '17 at 12:46
  • @NinaScholz If I am not mistaken, and haven't tested it, `new getClass()()` would call the `getClass` constructor with no parameters, then try to invoke the resulting instance, which would most likely result in an error of trying to invoke a non-function. –  Feb 28 '17 at 13:07
  • @torazaburo, the [precedence table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table) is saying, new goes first, the function, but with testing the part, the result is first function then new. – Nina Scholz Feb 28 '17 at 13:24
  • @NinaScholz I don't think this is a dup and it should be re-opened. –  Feb 28 '17 at 15:42

2 Answers2

1
 obj = new (getClass());

This means:

  1. Call the getClass function with no arguments (getClass()). That returns either String, or Array, or Object, the latter in this case.

  2. Call new on the return value from getClass(). In that case, that equates to new Object, which creates a new object.

1

You could use

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

which explain better whats happen. It calls the function getClass and returns an object for a new instance.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392