Cod*_*del 4 javascript node.js
我想从像"User.find"这样的字符串动态调用函数.如果函数存在,脚本将在对象User中调用函数find().这是我试过的:
var User = {};
User.find = function(){
return 1;
}
var input = 'User.find';
var some_data_array = {name: 'John Doe'};
var method = input.toString().split('.');
var nameObj = method[0].substring(0,1).toUpperCase() + method[0].substring(1);
var methodToCall = method[1];
nameObj.call(methodToCall, some_data_array);
Run Code Online (Sandbox Code Playgroud)
但它总会回归:
nameObj.call(methodToCall, some_data_array);
TypeError: Object User has no method 'call'
Run Code Online (Sandbox Code Playgroud)
任何的想法?我不能使用窗口,因为它是一个node.js问题,脚本不在浏览器中执行.
你完全是误会call().
call()让你用不同的方法调用方法this.
您希望按名称获取属性:
object[methodName](arg1, arg, ...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11055 次 |
| 最近记录: |