JavaScript adjunta dinámicamente funciones a objetos

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;
}

preguntado el 10 de marzo de 12 a las 05:03

4 Respuestas

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() funciona así:

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

Nota la 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);

Más información: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

respondido 10 mar '12, 05:03

El code as a String example is exactly what I was looking for, thx :) - munyul

EDITAR : The other post's Function(code) solution appears better. I did not know about that constructor.

A possible solution may be:

Object.prototype.attach = function(name,code) {
    this.name = function() {
        eval(code);
    };
}

respondido 11 mar '12, 09:03

eval definitely makes time complexity increased :) - Jinu José Daniel

Assuming that definition of function attach, you should call it like this:

attach(obj, fnName, function(){ alert(1); });

The way you invoked it is invalid syntax.

Also, as you may have noticed, that's not a very useful function, since you can do the same thing using your one-line function definition:

obj[fnName] = function(){ alert(1); });

respondido 10 mar '12, 05:03

You can attach them as function objects if they've already been defined, such as here: Javascript: better way to add dynamic methods?

You can also use the new Function constructor to dynamically define the functions, such as here: Creating functions dynamically in JS

Here is an explanation of the differences between eval and the new Function constructor: ¿Eval () y new Function () son lo mismo?

As a warning, use of eval() and the new Function constructor have created controversy and have been condemned (to some extent) by a number of individuals, such as here: Usos legítimos del constructor de funciones

Here is more information about eval: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Here is more information about the new Function constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

contestado el 23 de mayo de 17 a las 12:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.