Javascript:绑定到一个函数的权利? [英] Javascript: binding to the right of a function?

查看:86
本文介绍了Javascript:绑定到一个函数的权利?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能绑定到该功能的权利?示例:

How can I bind to the right of the function? Example:

var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9


推荐答案

您正在寻找部分功能,这些功能是便捷的别名简化方式。

You're looking for partial functions, which are convenient shorthands for aliases.

完成您要求的经典方式是:

The "classic" way to do what you're asking for is with:

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

使用部分函数将会是:

Using partial functions it would be:

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

不幸的是, Function.prototype.partial isn在任何浏览器中都没有。

Unfortunately, Function.prototype.partial isn't provided in any browser.

幸运的是,我一直在研究我认为的一个图书馆 JavaScript面向对象的函数,方法,类等等。这是 Function.prototype.partial.js

Fortunately for you, I've been working on a library of what I consider to be essential JavaScript object oriented functions, methods, classes, etc. This is 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);
            };
        };
    }
}());

这篇关于Javascript:绑定到一个函数的权利?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆