Javascript:绑定到函数的右边?

Mai*_*tor 5 javascript functional-programming

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

var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
Run Code Online (Sandbox Code Playgroud)

Esa*_*ija 11

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
Run Code Online (Sandbox Code Playgroud)


zzz*_*Bov 6

您正在寻找部分函数,​​它们是别名的方便缩写.

做你所要求的"经典"方式是:

var square = function (x) {
  return Math.pow(x, 2);
};
Run Code Online (Sandbox Code Playgroud)

使用部分函数将是:

var square = Math.pow.partial(undefined, 2);
console.log(square(3));
Run Code Online (Sandbox Code Playgroud)

遗憾的是,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);
            };
        };
    }
}());
Run Code Online (Sandbox Code Playgroud)