Javascript:绑定到函数的右侧

Javascript: binding to the right of a function?

本文关键字:函数 绑定 Javascript      更新时间:2023-09-26

如何绑定到函数的右侧?示例:

var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
Function.prototype.bindRight = function() {
    var self = this, args = [].slice.call( arguments );
    return function() {
        return self.apply( this, [].slice.call( arguments ).concat( args ) );
    };
};
var square = Math.pow.bindRight(2);
square(3); //9

您正在寻找分部函数,这对于别名来说是方便快捷的。

做你要求的事情的"经典"方法是:

var square = function (x) {
  return Math.pow(x, 2);
};

使用部分函数,它将是:

var square = Math.pow.partial(undefined, 2);
console.log(square(3));

不幸的是,任何浏览器都没有提供Function.prototype.partial


幸运的是,我一直在开发一个库,其中包含我认为重要的JavaScript面向对象的函数、方法、类等。这就是Function.prototype.partial.js:

/**
 * @dependencies
 * Array.prototype.slice
 * Function.prototype.call
 * 
 * @return Function
 * returns the curried function with the provided arguments pre-populated
 */
(function () {
    "use strict";
    if (!Function.prototype.partial) {
        Function.prototype.partial = function () {
            var fn,
                argmts;
            fn = this;
            argmts = arguments;
            return function () {
                var arg,
                    i,
                    args;
                args = Array.prototype.slice.call(argmts);
                for (i = arg = 0; i < args.length && arg < arguments.length; i++) {
                    if (typeof args[i] === 'undefined') {
                        args[i] = arguments[arg++];
                    }
                }
                return fn.apply(this, args);
            };
        };
    }
}());

Lodash的partialRight将执行您想要的操作,下面是文档:

这个方法类似于_.partial,除了分部参数被附加到提供给新功能的那些。自变量func(Function):要部分应用参数的函数。[arg](…*):要部分应用的参数。Returns(Function):返回部分应用的新函数。

这似乎需要部分应用程序。有许多库提供了这一功能,包括underscore.js:http://documentcloud.github.com/underscore/

您可以使用undercore.js中的partial,通过将_作为占位符传递,以便稍后填写:

var square = _.partial(Math.pow, _, 2);
console.log(square(3)); // => 9

此功能出现在2014年2月(下划线1.6.0)。

有什么问题

var square = function(x) {return x*x;};

为了正确回答这个问题,您需要创建一个匿名函数,该函数使用一个设置的参数调用"绑定"函数,例如:

var square = function(x) {return Math.pow(x,2);};

通过这种方式,可以绑定任意数量的参数、重新排列参数或两者的组合。但是,请记住,这会对性能产生一些影响,因为每次像这样绑定时,都会向堆栈添加一个额外的函数调用。