How to bind function arguments without binding this?

前端 未结 15 953
爱一瞬间的悲伤
爱一瞬间的悲伤 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:57

    Well for the exemple you gave, this will do

    var b= function(callback){
            return obj.c(1,2,3, callback);
    };
    

    If you want to guarenty enclosure of the parameters :

    var b= (function(p1,p2,p3, obj){
            var c=obj.c;
            return function(callback){
                    return c.call(obj,p1,p2,p3, callback);
            }
    })(1,2,3,obj)
    

    But if so you should just stick to your solution:

    var b = obj.c.bind(obj, 1, 2, 3);
    

    It's the better way.

提交回复
热议问题