Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dynamically attaching functions to objects

How to attach a function dynamically to a javascript object.For ex: if the function for dynamic attachment is attach(),then i should be able to attach the function fn to onject obj as follows..

attach(
     obj,fn,{
                  alert(1)
            }
      )


function attach(obj,fnName,code)
{
    obj[fnName] = code;
}
like image 867
Jinu Joseph Daniel Avatar asked Mar 10 '12 05:03

Jinu Joseph Daniel


People also ask

Can you put functions in objects JavaScript?

As mentioned, functions are objects. You can work with functions as if they were objects. For example, you can assign functions to variables, to array elements, and to other objects. They can also be passed around as arguments to other functions or be returned from those functions.

How do you append property to an object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

What is dynamic functionality in JavaScript?

The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.

Are objects in JavaScript dynamic?

A JavaScript object is syntactically defined as a function, which is itself a first instance and that is cloned to create more instances. In addition, this structure is dynamic, methods (in fact inner functions) and attributes may be added during the execution of the script.


1 Answers

If by "attach a function dynamically to a javascript object" you mean "add a function-object as an object property" then the syntax you've already shown is almost right. This is what it should be:

var fnName = "testFunc";
obj[fnName] = function() { alert("Test function"); };
// or
obj.testFunc = function() { ... };
// or
obj[fnName] = nameOfFunctionDefinedElsewhereInCurrentScope;

Which means you could call your attach() function like this:

// attach an anonymous function:
attach(obj, "newFunctionName", function() { alert(1); });
// attach a function defined elsewhere
attach(obj, "newFunctionName", someFunction);

Note: the attach() function really doesn't save any effort at all, in fact it just gives you more characters to type...

By the way (but don't do this), if the parameter you want to pass as code is a string of code do this:

var code = "alert(0);";
obj[fnName] = new Function(code);

More information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

like image 121
nnnnnn Avatar answered Nov 07 '22 05:11

nnnnnn