How to invoke function in namespace?

Hi,

I know function name can be invoke by string using the following:

window[functionName]

but how do I use this for namespace function i.e. myname.function ?

Hi does anybody know the above?
Thanks in advanced.

It should be in the same way.


var DOG = {
    eat: function () {
        return 'Nom nom nom.';
    },
    speak: function () {
        return 'Woof!';
    }
};

var action = 'speak';
alert( DOG[action]() );


var DOG = {
    eat: function () {
        return 'Nom nom nom.';
    },
    speak: function () {
        return 'Woof!';
    }
};

var action = 'DOG.eat';
alert( action() );

Hi Paul,
what I hope to achieve is instead the above. Is it possible?

No, you cannot because the individual methods are not stored within the object in that manner.

You can though achieve similar by using the window to store the namespace, so that you can then later on retrieve it.


window.DOG = {
    ...
};
var action = {namespace: 'DOG', method: 'speak'};
alert( window[action.namespace][action.method]() );

If you instead use ‘DOG.speak’ you will need to use more complex ways to retrieve the appropriate info.


var action = 'DOG.speak';
alert( window[action.split('.')[0]][action.split('.')[1]]() );

This works.
var DOG = {eat: function (){ return ‘Nom nom nom.’;}, speak: function (){ return ‘Woof!’; } }

var action = DOG.eat;
alert( action() );

or

alert(DOG.eat())

Yes, using action = DOG.eat will work, but only if you keep in mind that it’s an object, not a string as requested by the OP.

Yes Allan, this is what I currently have on first load, but after subsequent refresh, I am storing the namespace.method name in an input hidden field, that is why needed to find a solution to invoke using string.

Thanks Paul, how about is there a way to get the name of the object? For example:


var action = DOG.speak; // <-- is an object
alert( DOG.speak.toString( ) ) // <-- was hoping to get the name "DOG.speak" but this doesn't work

No, not that I know of, because DOG.speak is not the textual representation, it is instead a reference that is pointing to the actual function.

ok lol, I reckon this coming. Now I have to pass it like so:

function( callback, callbackString )

Thanks alot for your advise Paul, really appreciate your help.