0

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() {
        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

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

4 Comments

Aah accessing the function as an array element. Awesome.
As for the globals in my real code I'm using this.callFoo(), this.construct(), etc - doesn't that have the same result as declaring with var?
@willoller you have to do this.construct = .... construct = ... writes to global scope instead.
Yeah that's what I meant. Thanks!
0

try this:

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.