javascript将对象方法传递给不同的对象方法

标签 javascript oop design-patterns

我有一个 bar 类型的对象,它有一个由许多 foo 组成的数组。

我希望能够动态调用 foo 的方法 - 我可以通过传递字符串来使用 eval 来执行此操作,但我更愿意了解如何调用传递函数。

从概念上讲,我这样做的方式正确吗?

var foo = function() {
    this.methodA = function() {
        return "a";
    };
    this.methodB = function() {
        return "b";
    };
};

var bar = function() {
    var foos = [];

    this.construct = function() {
        foos[0] = new foo();
    }; this.construct();

    this.callFoo = function(f) {
        return foos[0].f();
    };
};

b = new bar();
b.callFoo(foo.methodA); //<-- This doesn't work
b.callFoo(methodA); //<-- Or this

最佳答案

到处都是你泄漏的全局变量。

// global leak
foo = function() {

    // global leak
    methodA = function() {
        return "a";
    };
    // global leak
    methodB = function() {
        return "b";
    };
};
// global leak
bar = function() {
    var foos = [];
    // global leak
    construct = function() {
        foos[0] = new foo();
    };construct();

    this.callFoo = function(f) {
        return foos[0].f();
    };
};

b = new bar();
b.callFoo(foo.methodA); //<-- This doesn't work
b.callFoo(methodA); //<-- Or this

要回答实际问题,请尝试此操作。

var foo = function() {
    return {
        methodA: function() { return "a"; },
        methodB: function() { return "b"; }
    };
}

var bar = function() {
    var foos = [];

    return {
        construct: function() {
            foos.push(foo());
        },
        callFoo = function(name) {
            return foos[0][name]();
        }
    }
}

b =  bar();
b.callFoo("methodA");

关于javascript将对象方法传递给不同的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5748055/

相关文章:

java - 当私有(private)函数需要调用公共(public)函数时如何改进?

java - SQL 请求和循环结果最佳模式

javascript - 如何在 "AktionLink"的 "onClick"事件中调用 "div"?

javascript - WebGL 在页面上崩溃时的事件?

javascript - 安全帽 : Issues while deploying a NFT to rinkeby network

java - 抽象类以摆脱 Activity 中的冗余代码

c++ - 模板函数 : perform conversion based on typename

javascript - highcharts范围线问题

java - 正确使用聚合(OOP)以电子电路类为例

c# - 您如何使用 C# WinForms 在 MVP 中的 View 之间导航?