Javascript反射,调用带有字符串的方法
Javascript reflection, call a method with a string
var OrderDetails = function () {
var orderdetails = {};
orderdetails.doSomething = function(){
alert('do something');
};
return orderdetails;
}
在代码的其他地方...
processMethod('doSomething')
function processMethod(strMethod)
{
// strMethod = 'doSomething';
var orderdet = OrderDetails(); //not the exact instantiation, just illustrating it is instantiated
orderdet.strMethod(); //this is the line I'm stuck with.
}
我目前正在尝试通过 Javascript 中的字符串名称调用一个方法。我已经将apply,call和eval()视为此问题的潜在解决方案,但似乎无法让它们中的任何一个工作。有人对我的特定对象场景的语法有任何指导吗?
使用括号表示法而不是点表示法:
orderdet[strMethod]();
这应该有效。 processMethod('doSomething')
function processMethod(strMethod)
{
// strMethod = 'doSomething';
var orderdet = OrderDetails(); //not the exact instantiation, just illustrating it is instantiated
orderdet[strMethod](); //this is the line I'm stuck with.
}
相关文章:
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 在JavaScript中拆分日期字符串的更好方法是什么
- 用Javascript重新格式化复杂文本日期字符串的更好方法
- 用javascript修复这个JSON对象字符串最干净的方法是什么
- jQuery字符串使用split()方法在空格后拆分字符串
- 使用查询字符串方法清除浏览器缓存
- 使用子字符串方法时应用程序挂起的原因
- 使用字符串方法更改Javascript对象中的DOM元素参数
- 在Javascript中对对象属性执行字符串方法
- 直接访问字符串方法
- 尝试我自己的字符串方法来删除元音
- 对字符串方法的ajax调用不起作用
- 字符串方法精确文本
- 如何在字符串原型扩展方法中使用字符串方法
- 有没有任何字符串方法,能让我把一串数字,转换成一串数字和字母
- 字符串方法
- 在定义新的字符串方法时使用reduce()
- 问题与自定义大写字符串方法,jQuery和Select2
- 使用比较字符串方法或使用==验证密码字段,但两者都不起作用
- 如何防止javascript缓存?查询字符串方法不起作用