开发者

javascript pass object method to different object method

I have an object of type bar which has an Array of many foos.

I want to be able to call a method of foo dynamically - I could do this with eval by passing a string, but I would rather get a handle on how to pass the function.

Am I - conceptually - doing this the right way?

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

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

    this.construct = function() {
        fo开发者_开发百科os[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


your leaking globals everywhere.

// 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

To answer the actual question try 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");


try this:

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜