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

后端 未结 30 2713
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:08

    You can't call a constructor with a variable number of arguments like you want with the new operator.

    What you can do is change the constructor slightly. Instead of:

    function Something() {
        // deal with the "arguments" array
    }
    var obj = new Something.apply(null, [0, 0]);  // doesn't work!
    

    Do this instead:

    function Something(args) {
        // shorter, but will substitute a default if args.x is 0, false, "" etc.
        this.x = args.x || SOME_DEFAULT_VALUE;
    
        // longer, but will only put in a default if args.x is not supplied
        this.x = (args.x !== undefined) ? args.x : SOME_DEFAULT_VALUE;
    }
    var obj = new Something({x: 0, y: 0});
    

    Or if you must use an array:

    function Something(args) {
        var x = args[0];
        var y = args[1];
    }
    var obj = new Something([0, 0]);
    

提交回复
热议问题