binding/applying constructors in JavaScript

前端 未结 2 1647
后悔当初
后悔当初 2020-12-31 08:46

I was looking for solutions for calling Javascript constructors with an arbitrary number of arguments, and found some good SO posts, which led me to believe that these three

2条回答
  •  无人及你
    2020-12-31 09:34

    bind and apply / call only works work invocation to function but not constructor, so basically with native methods you cannot do this, one way is to write a bindConstruct method but it may involves extra complexity:

    function bindConstruct(fn) {
        // since constructor always accepts a static this value
        // so bindConstruct cannot specify this
        var extraArgs = [].slice.call(arguments, 1);
    
        // create a 'subclass' of fn
        function sub() {
            var args = extraArgs.concat([].slice.call(arguments));
            fn.apply(this, args);
        }
        sub.prototype = fn.prototype;
        sub.prototype.constructor = sub;
    
        return sub;
    }
    

    This, actually, creates a subclass to your constructor.

    Then your code:

    var MyClass = function(x, y) {
        console.log(arguments);
        console.log(x + y);
    }
    var BindedMyClass = bindConstruct(MyClass, 1, 2, 3);
    var c = new BindedMyClass(4, 5);
    console.log(c instanceof MyClass);
    console.log(c instanceof BindedMyClass);
    

    You may also write this function to Function.prototype or as an extension to the native bind function.

提交回复
热议问题