1

So, suppose I have these two functions:

var foo = function() {
    this.message = "fooBar";
    this.fooBar = function() {
        console.log(this.message);
    };
};

and

var goo = function() {
    this.message = "gooBar";
    this.gooBar = function() {
        console.log(this.message);
    };
};

Then, suppose I have these two arrays:

var Foos = [];
var Goos = [];

And somewhere in the program, I push new instances of the corresponding function into the arrays (new foo into Foos, and new goo into Goos). Now, I want to call the methods. So, I could do this for Foos:

for(var i = 0; i < Foos.length; i ++) {
    Foos[i].fooBar();
}

and then this for Goos:

for(var i = 0; i < Goos.length; i ++) {
    Goos[i].gooBar();
}

When I have a lot of functions (which I do for my program), doing this gets a bit tedious. And my program also gives the functions more than one method. But some functions only have one. Yet others have five. So, I thought, why not use the Array object, like so:

Array.prototype.apply = function() {
    for(var i = 0; i < this.length; i ++) {
        this[i].CALL_METHODS();
    }
};

Then I could store all the arrays in an array, and call apply on every element in that array. But, .CALL_METHODS() isn't an actual method (of course). So, is there any way that I can accomplish this, calling all the methods of instances, no matter the number of methods nor the names?

Thanks in advance!

1 Answer 1

1

im sure there must be actual real way of doing this in javascript... one question why would you want to call any method declared in javascript object just like that? there must be some design pattern available to ur problem but need to search... while reading just started typing some code :) so here is just attempt to call all functions in any possible way i could thought of (very bad way possibly) :(

var foo = function() {
    this.message = "fooBar";
    this.fooBar = function() {
        alert('im from foobar');
    };
    this.fooBar1 = function() {
        alert('im from foobar 1');
    };
};
var goo = function() {
    this.message = "gooBar";
    this.gooBar = function() {
        alert(this.message);
    };
};
var f1=new foo();
var f2=new foo();
var g1=new goo();
var Foos=[];
Foos[0]=f1;
Foos[1]=f2;
Foos[2]=g1;
for (index = 0, len = Foos.length; index < len; ++index) {
    var dummy=Foos[index];
    console.log(dummy);
    for(c in dummy){
        var m='dummy.' + c.toString(); 
        if(eval(m+'.call')!=undefined){
            eval(m + '()');
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it didn't work out. Thanks for trying, though! :)

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.