Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 2761
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  一整个雨季
    2020-11-22 01:16

    Any function (even a constructor) can take a variable number of arguments. Each function has an "arguments" variable which can be cast to an array with [].slice.call(arguments).

    function Something(){
      this.options  = [].slice.call(arguments);
    
      this.toString = function (){
        return this.options.toString();
      };
    }
    
    var s = new Something(1, 2, 3, 4);
    console.log( 's.options === "1,2,3,4":', (s.options == '1,2,3,4') );
    
    var z = new Something(9, 10, 11);
    console.log( 'z.options === "9,10,11":', (z.options == '9,10,11') );
    

    The above tests produce the following output:

    s.options === "1,2,3,4": true
    z.options === "9,10,11": true
    

提交回复
热议问题