How to bind function arguments without binding this?

前端 未结 15 934
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 07:25

In Javascript, how can I bind arguments to a function without binding the this parameter?

For example:

//Example function.
var c = funct         


        
15条回答
  •  情话喂你
    2020-11-30 07:41

    In the native bind method the this value in the result function is lost. However, you can easily recode the common shim not to use an argument for the context:

    Function.prototype.arg = function() {
        if (typeof this !== "function")
            throw new TypeError("Function.prototype.arg needs to be called on a function");
        var slice = Array.prototype.slice,
            args = slice.call(arguments), 
            fn = this, 
            partial = function() {
                return fn.apply(this, args.concat(slice.call(arguments)));
    //                          ^^^^
            };
        partial.prototype = Object.create(this.prototype);
        return partial;
    };
    

提交回复
热议问题