如何将函数动态附加到对象 [英] How to dynamically attach a function to an object

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

问题描述

我知道 SO 中已经存在一些类似的问题( 1 2 3 ),但是很遗憾,我对 JS 不允许我将方案推断到我的个人用例,因此是这个问题。

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, hence this question.

我有以下代码这使我可以动态地附加到对象并从对象中调用某些函数,这些函数工作正常(在<$ c $上可用c> JsFiddle ):

I have the following piece of code which allows me to dynamically attach to and call from an object some functions, which works fine (available on JsFiddle):

JavaScript

$.extend(true, window, {
    "MyPlugin": {
        "dynamicFunction": dummy_function
     }                
});

function dummy_function() {

}

function real_function(string) {
    alert(string);
}

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

HTML:

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

更新:

很有趣,我正在尝试复制一个问题,据此我可以使用我的函数是在本地范围内的,但是我结束了写一个不是的示例:)(我告诉过 JS 不是我的事)。因此,所有 window [function_name] 的答案都是正确的,尽管我接受了 James Allardice 的原因,因为他推断出了我的问题

Funny enough, I was trying to replicate an issue I have whereby my function is scoped locally, but I ended writing an example where it isn't :) (I told you JS isn't my thing). Therefore all window[function_name] answers are correct, although I accepted James Allardice's because he extrapolated to the issue I was trying to resolve but didn't raise.

如何在不使用 eval 的情况下实现相同的功能?

How can I achieve the same functionality without the use of eval?

推荐答案

全局范围内的函数声明成为窗口,因此您可以使用方括号语法:

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

function dynamic_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];

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆