【问题标题】:Functions as parameters (with parameters) -- JavaScript函数作为参数(带参数)——JavaScript
【发布时间】:2009-04-10 14:32:15
【问题描述】:

如果我有一些看起来像这样的 OO javascript:

function someFunction(a, b, c) {
  // do something with a, b, and c
}

function theLoader() {
    loadFunction: someFunction,
    load: function() {
      // invoke the loadFunction with the proper parameter set
    }
}

var myLoader = new theLoader();
myLoader.load();

让我们假设“theLoader”应该是抽象的和通用的。我可以调用它并将“loadFunction”设置为几乎任何东西,所以我不知道在任何给定时间参数会是什么。 'load' 方法必须调用 'loadFunction' 并且能够以某种方式获取为其设置的参数....

我怎样才能完成我想做的事情?如果这是一个不好的方法,我们可以完全重构代码。我想保持对'loadFunction'的限制,所以我不必以特殊方式编写加载器函数。

归根结底,我想将加载器打包到它自己的 .js 文件中,而不必胡思乱想。

所以——如果你知道答案,请帮助兄弟!

谢谢, g

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用applycall 执行函数调用。可在此处找到功能说明:

    【讨论】:

    • 我一直在调查申请。不过,鉴于 loadFunction 不是实际的函数名称,我可以只使用 loadFunction.apply(this, arguments) 吗?
    • 是的,apply 和 call 都是 Function 对象的方法。
    【解决方案2】:

    你应该让你的loadFunction 遵循一个接口,并使用多态性来调用它。话虽如此,您确实需要以some 方式捕获someFunction 的参数。

    你能允许load 函数获取loadFunction 需要的参数吗?

    myLoader.load(1, '2', 'foo'); // calls this.loadFunction(1, '2', 'foo')
    

    或者,允许theLoader 将它们带入构造函数?

    function theLoader() {
        this.loadFunctionArgs = arguments;
    }
    
    theLoader.prototype = {
        loadFunction: someFunction,
        load: function() {
            return this.loadFunction.apply(this, this.loadFunctionArgs)
        }
    }
    
    var myLoader = new theLoader(1, '2', 'foo');
    myLoader.load(); // calls someFunction(1, '2', 'foo')
    

    我不知道这是否适合您的应用程序。用 JavaScript 做当然没问题(就语言而言,我的意思是)。

    【讨论】:

    • 这是个好建议。为简单起见,我尽量保持抽象,但实际上看起来更像这样(下一条评论)
    • function customerDataLoader(customerID) { stuff } function customerInvoiceLoader(customerID, orderNumber) {stuff} custLoader = new theLoader({loadFunction: customerDataLoader}); invoiceLoader = new theLoader({loadFunction: invoiceDataLoader});参数值不是静态的。
    【解决方案3】:

    我认为您正在寻找的是:

    function theLoader() {
        this.load = function() {
            if (this.loadFunction) {
                return this.loadFunction.apply(this, arguments);
            }
        };
    }
    // Usage
    var loader = new Loader();
    loader.loadFunction = someFunction;
    loader.load(1, 2, 3, 4);
    

    此外,您将对象文字符号与函数文字混合在一起,这是不正确的。

    【讨论】:

    • Helgi - 感谢您的提示。我对点表示法和对象文字表示法有点模糊。你的例子和指针是一个巨大的帮助。
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多