如何在JS中使用动态名称调用函数 [英] How to call a function using a dynamic name in JS

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

问题描述

我正在尝试按照下面发布的示例将其称为函数。所以问题是我用来调用该函数的方法不起作用...我需要类似的东西,因为我将通过监听事件来调用这些函数。有人知道马上这样做吗?

I'm trying to call this a function following the same example that I've posted bellow. So the problem is that the method that I'm using to call the function doesn't work... I need something like that cuz I'm going to call those functions through listening events. Some one knows the right away to do it?

Thx。

//variables
var ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = "function test0(){  alert(" + da + "); }";
s[0] = "function test1(){  alert(" + ta +"); }";

//"Register" the function
for(i=0; i< s.length; i++){
	eval(s[i]);
}

// calling the function
this["test"+1];

推荐答案

通常,我们应该避免评估。无需使用eval并使用更简单的代码,您可以尝试执行以下操作:

Usually we should avoid eval. What you are trying to do is possible without using eval too and with a simpler code :

//variables
var ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = function test0(){  alert(" + da + "); };
s[0] = function test1(){  alert(" + ta +"); };

s.forEach((fun) => { this[fun.name] = fun;});

// calling the function
this["test"+1]();

或者在您的代码中做简单的事情:

Or simple in your code do :

this["test"+1]();

编辑:

如果使用string和eval只是因为您将函数名作为字符串获取,而是可以创建一个对象:

If you are using string and eval just because you are getting function name as string, instead you can create an object :

var data = {};
for(var i = 0; i<10; i++) {
  data['key'+ i] = function (i) { alert(i); }.bind(null, i);
}

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

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