本文介绍了Javascript动态将函数附加到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将函数动态附加到javascript对象.例如:如果用于动态附加的函数是attach(),那么我应该能够将函数fn附加到onject obj上.

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

推荐答案

如果通过将函数动态附加到javascript对象"来表示将函数对象作为对象属性添加",那么已经显示的语法几乎是正确的.这应该是这样:

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;

这意味着您可以像这样调用attach()函数:

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

注意:attach()函数实际上根本不节省任何精力,实际上它只是为您提供了更多可键入的字符...

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

顺便说一句(但不要这样做),如果要作为code传递的参数是一串代码,请执行以下操作:

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

更多信息: https://developer.mozilla.org/en/JavaScript /Reference/Global_Objects/Function

这篇关于Javascript动态将函数附加到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 15:48