-1

I would like to have a Javascript object obj that contains an array of other objects and is able to call their methods. I would also want any object to be able to register into the array by calling a special function of the object obj and pass a reference of itself as an argument.

Would anybody be so kind and help me with that, please? I've been having a hard time with it.

Also I thought of a simple solution where the object obj creates all the other objects but that doesn't seem to work as well...

Golemp
  • 1

1 Answers1

1

Perhaps you mean something like this

function Invoker(arr) {
    arr = arr.slice();
    arr.invoke = function (methodName) {
        var args = Array.prototype.slice.call(arguments, 1),
            i;
        for (i = 0; i < this.length; ++i)
            if (methodName in this[i])
                this[i][methodName].apply(this[i], args);
    };
    return arr;
}

var arr = [
    {foo: function (a, b) {console.log('foo', a);}},
    {foo: function (a, b) {console.log('bar', b);}}
];
var invkr = Invoker(arr);
invkr.invoke('foo', 'hello', 'world');
/*
  foo hello
  bar world
*/
Paul S.
  • 64,864
  • 9
  • 122
  • 138