javascript: 默认情况下总是将函数中的第 n 个参数作为固定值传递

javascript: always pass the nth argument in a function as fixed value by default

该函数需要 3 个参数,例如

function p(x,y,z){
 console.log(arguments);
}

所以当我们这样称呼它时 p(12,21,32)

第四个参数应该传递为 56

所以有效的调用应该是 p(12,21,32,56)

如何操作?

条件我们无法更改函数定义。我需要将第四个参数部分绑定为 56,例如

p=p.bind(这个,'','','',56); 或者使用 lodash

然后像

一样稍后调用p

p(12,21,32);

这样 56 应该默认通过

p = (function() {
    var old_p = p;
    return function(a, b, c) {
        return old_p(a, b, c, 56);
    };
})();

我们记得名称为 old_pp 的旧版本,因此即使在我们重新定义 p 之后也可以调用它。我们在 IIFE 内部执行此操作,以便 old_p 不会污染全局范围。然后,我们 return 一个函数(分配给 p),它 return 是使用额外参数调用 old_p 的结果。

我们可以使它更通用,创建 "bound" 函数,为任何函数调用添加额外的参数。下面我使用 ES6 语法,尤其是扩展 ... 运算符。但是,您可以通过操作 arguments 对象并使用 apply:

来完成同样的事情
function bind_with_arguments_at_end(f, ...extra_args) {
    return function(...args) {
        return f(...args, ...extra_args);
    }
}

如果所涉及的函数是对象上的方法,"pass through" this 是有意义的,因此可以将新函数调用为 this.bound_func 并且事情会继续进行。这样做,我们可以使用 call:

function bind_with_arguments_at_end(f, ...extra_args) {
    return function(...args) {
        return f.call(this, ...args, ...extra_args);
               ^^^^^^^^^^^
    }
}

复制原件并覆盖名称,并使用新参数调用原件。

function p(a,b,c,d) {
   console.log(arguments);
}

(function (){
    var org_p = p;  //copy original
    p = function() {  //override p
        var args = [].slice.call( arguments );  //turn arguments in to array
        args.push(56);  //add the 4th argument
        return org_p.apply( this, args );  //call the original with the updated arguments.
    }
}());

p(1,2,3);

您可以使用 _.partialRight() 创建一个新函数,将参数附加到原始函数的末尾:

function p(a, b, c)
{
  alert([].join.call(arguments, ','));
}

p = _.partialRight(p, 56);
p(1,2,3); // 1,2,3,56
<script src="https://raw.githubusercontent.com/lodash/lodash/3.9.3/lodash.js"></script>

要准确指定额外参数的位置,您可以使用占位符:

p = _.partialRight(p, _, _, _, _, _, _, 56); // add 56 as 7th arg
p(1,2,3); // 1,2,3,,,,56

您可以创建一个使用 apply to redirect its arguments to the original one, but using Object.assign 覆盖其中一些的新函数:

function fixArguments(f, args) {
  return function() {
    return f.apply(this, Object.assign([].slice.call(arguments), args));
  };
}
p = fixArguments(p, {3: 56}); // Overwrite the 4th argument with 56

function fixArguments(f, args) {
  return function() {
    return f.apply(this, Object.assign([].slice.call(arguments), args));
  };
}
function p(x,y,z){
  console.log(arguments);
}
p = fixArguments(p, {3: 56});
p(12,21,32);