在JS中动态创建函数 [英] Creating functions dynamically in JS

查看:3283
本文介绍了在JS中动态创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为JS游戏创建AI引擎,它由有限状态机构成。我正在从XML加载状态数和它们的变量值。我也想加载行为,因为我没有时间创建脚本语言,我认为将JS代码插入外部文件(在XML节点内)并在上面执行它是个好主意。需求。

I am creating the AI engine for a JS game, and it's made of Finite State Machines. I am loading the number of states and their variable values from the XML. I also want to load the behaviour, and since I don't have the time to create a scripting language, I thought it would be a good idea to 'insert' JS code on external files (inside XML nodes), and execute it on demand.

类似的东西

<evilguy1>
    <behaviour>
        this.x++;
    </behaviour>
    <behaviour>
        this.y++;
    </behaviour>
</evilguy1>

这样的事情:

function behaviour_1(){
    this.x++;
}
function behaviour_2(){
    this.y++;
}

我的问题是,现在我已经加载了代码,我该怎么执行它?我想为每个代码'node'创建一个具有唯一名称的函数,然后从游戏逻辑中调用它们,但我不知道这是否可行(因为你可以从HTML加载更多的JS代码,你也应该能够从JS代码中做到这一点,没有?)。如果没有,有没有类似的解决方案?提前致谢!

My question is, now that I have the code loaded, how can I execute it? I would like to create a function with an unique name for each code 'node', and then call them from the game logic, but I don't know if this is possible (Since you can load more JS code from the HTML, you should also be able to do it from the JS code, no?). If not, is there any similar solution? Thanks in advance!

(PS:外部库依赖性越小越好)

(PS:The less external-library-dependent, the better)

编辑1 :

好的,现在我知道如何创建包含代码的函数

Ok, so now I know how to create functions to contain the code

window[classname] = function() { ... };


推荐答案

好吧,你可以用函数构造函数,如下例所示:

Well, you could use Function constructor, like in this example:

var f = new Function('name', 'return alert("hello, " + name + "!");');
f('erick');

这样你就可以用参数和body定义一个新函数,并将它赋值给变量f。您可以使用哈希集并存储许多函数:

This way you're defining a new function with arguments and body and assigning it to a variable f. You could use a hashset and store many functions:

var fs = [];
fs['f1'] = new Function('name', 'return alert("hello, " + name + "!");');
fs['f1']('erick');

加载xml取决于它是在浏览器还是服务器上运行。

Loading xml depends if it is running on browser or server.

这篇关于在JS中动态创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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