【问题标题】:Add parameter to function dynamically [closed]动态添加参数到函数[关闭]
【发布时间】:2013-10-31 15:09:36
【问题描述】:
// set Process
i18n.setProcess(function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff') });

// Setter and getter 
this.setProcess = function( opProcess ) {  //here param opProcess is function with parameters see i18n.setProcess() line of code
        if( opProcess == undefined) 
            throw "Process is undefined";
        if( $.isFunction(opProcess) == false )
            throw "Process is not a function"
             process = opProcess;

    };
    this.getProcess = function() {
        return process;
    };

了解 i18n.setProcess 如何将带有参数的函数作为参数传递给 setProcess。

现在我在 SetProcess 中想要的是 function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff',**id**) // id 被动态添加到作为参数传递给 setProcess 的函数本身

问题 - 我想在设置过程中动态添加 id(在我的类变量中定义,总是可以通过 id 访问)并添加函数参数(Url 等,等等,id)。函数参数可以增长,但id应该作为参数添加到最后?

尝试了很多解决方案但没有成功?检查here

【问题讨论】:

  • P.S 我还没有发布代码,因为它的巨大只是发布了我想做的事情,如果这就是反对票的原因

标签: javascript jquery


【解决方案1】:

这就是arguments 对象的用途..

function foo() {
    var lastArg = arguments.length ? arguments[arguments.length - 1] : 'default';
    return lastArg;
}

foo();     // "default"
foo(1);    // 1
foo(1, 2); // 2

如果你想编写一个类似于bind 的函数,它只在末尾添加参数,那么你可以这样做

function appendArguments(fn) {
    var slice = Array.prototype.slice.call.bind(Array.prototype.slice),
        args = slice(arguments, 1);
    return function () {
        return fn.apply(this, slice(arguments).concat(args));
    };
}

现在

var bar = appendArguments(foo, 3);
bar();     // 3
bar(4, 5); // 3 (because it's calling `foo(4, 5, 3)`

【讨论】:

  • arguments.length 总是给 0 我在发布之前尝试过
  • @inputError 您似乎将foo.lengtharguments.length 内部foo 混淆了。
  • 但我的问题是,当我将 opProcess 分配给进程时。我还没有调用进程函数。我想在调用它之前将 id 添加到处理函数的参数
  • 我只能从函数内部访问参数对象,而不是在此之前
  • @inputError 请看编辑,我想这次我理解你了。不过,这个问题还不清楚。
猜你喜欢
  • 2011-02-16
  • 1970-01-01
  • 2013-11-09
  • 2013-04-26
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 2013-04-22
相关资源
最近更新 更多