Forum Moderators: open
function myObj()
{
function add(f)
{
var fcall = f;
if( typeof f!= "function" )
{
fcall = new Function(f);
}
this.funcs[this.funcs.length] = fcall;
}
function execute()
{
for( var i = 0; i < this.funcs.length; i++ )
{
this.funcs[i](); // Call the function
}
}
this.funcs = new Array();
this.add = add;
this.execute = execute;
}
function hello()
{
alert("hello");
}
var foo = new myObj();
foo.add(hello);
foo.execute();
However, suppose I have this function:
function goodbye( name )
{
alert( "Goodbye " + name );
}
How can I add that?
You can add it, but how would you like to specify the argument when it is called?
You call the series of functions like this:
foo.execute();
..but since you don't know what position in the array the function requiring an argument is, you can't specify it. We need a little more information from your good self.
I have messed around with you code a little..
(Changed the constructor function to 'FnArray')
- Avoid defining the methods inside the constructor. This is inneficient, and causes closures (although they're fun too). These methods can be inherited via prototype.
- There is a branch in the 'add' method for defining a function if a string is passed instead of a function (I assumed). The little wiggle with the variable 'fcall' wasn't needed. I have added such a call.
function FnArray()
{
this.funcs = new Array;
}FnArray.prototype.add = function(f)
{
if( typeof f!= "function" )
{
f = new Function(f);
}
this.funcs[this.funcs.length] = f;
}FnArray.prototype.execute = function()
{
for( var i=0; i<this.funcs.length; i++ )
{
this.funcs[i]();
}
}function hello(){ alert("hello"); }
function goodbye( name ){ alert( "Goodbye " + name ); }var foo = new FnArray();
foo.add(hello);
foo.add("alert('function from string')");
foo.execute();
You can add it, but how would you like to specify the argument when it is called?
I'm thinking of something along the lines of this:
var foo = new myObj();
foo.add(hello);
foo.add(goodbye("Peter")); // That won't work though
foo.execute();
In other words, the argument(s) would be included when the function was added. Also, ideally, it would be dynamic such that I could have any number of arguments, or none at all.
Any ideas?
function goodbye(name){ alert("goodbye "+name); }function someFunction()
{
var aName = "Eric Local"
foo.add( function(){ goodbye(aName)} );
foo.add( "goodbye(aName)" );
}var aName = "Paul Global"
var foo = new FnArray();
someFunction()foo.execute();