Skip to content Skip to sidebar Skip to footer

How To Dynamically Attach A Function To An Object

I know there are a few similar questions already on SO (1, 2, 3) but unfortunately my limited knowledge of JS doesn't allow me to extrapolate the scenarios to my personal use case,

Solution 1:

Function declarations in the global scope become properties of window, so you can use square bracket syntax:

functiondynamic_call(function_name, text) {
    MyPlugin["dynamicFunction"] = window[function_name];
    MyPlugin["dynamicFunction"](text);
}​

If your function is not in the global scope, you could make it the value of a property of some object:

var myFuncs = {
    real_function: function () {
        alert(string);
    }
};

Then you can simply use:

MyPlugin["dynamicFunction"] = myFuncs[function_name];

Solution 2:

You cannot do this without eval if the function is scoped locally. You can only do it without eval if the function is property of some object. This includes global object, so global functions can be done without eval.

With a global function or function that is property of some object:

MyPlugin["dynamicFunction"] =window[function_name];//windowreferencesglobal object

Solution 3:

If real_function is a gloabl function, you just call

window[function_name](text);

Solution 4:

I know this is not the exact question, but if you can just pass in the function as a parameter, like this:

<button onClick="dynamic_call(real_function,'some text');">click me</button>​

function dynamic_call(f, text) {
   MyPlugin["dynamicFunction"] = f;
   MyPlugin["dynamicFunction"](text);
}​

Solution 5:

Instead of using eval, reference function_name from the window object:

MyPlugin["dynamicFunction"] = window[function_name];

Post a Comment for "How To Dynamically Attach A Function To An Object"