dynamic object construction in javascript?

后端 未结 4 1504
日久生厌
日久生厌 2020-12-01 11:08

When I want to call a function in javascript with arguments supplied from elsewhere I can use the apply method of the function like:

array = [&qu         


        
4条回答
  •  眼角桃花
    2020-12-01 11:22

    From developer.mozilla: Bound functions are automatically suitable for use with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. However, provided arguments are still prepended to the constructor call.

    That said, we still need to use apply to get the arguments out of an array and into the bind call. Further, we need to also reset bind's function as the this argument of the apply function. This gives us a very succinct one-liner that does exactly as needed.

    function constructorApply(ctor, args){
        return new (ctor.bind.apply(ctor, [null].concat(args)))();
    };
    

提交回复
热议问题