我能否通过字符串调用一个对象方法?我想像是这样的:
var FooClass = function() {
this.smile = function() {};
}
var method = "smile";
var foo = new FooClass();
// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();
我能否通过字符串调用一个对象方法?我想像是这样的:
var FooClass = function() {
this.smile = function() {};
}
var method = "smile";
var foo = new FooClass();
// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();
[]
。foo[method]();
可以通过数组表示法访问对象的属性:
var method = "smile";
foo[method](); // will execute the method "smile"
var obj = {talk: function(){ console.log('Hi') }};
obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
使用eval方法调用函数可能不是很好的方式。
eval("foo." + method + "()");
foo
是{fields:[{id:1}]}
,而method
是fields [0]?.id
,但我不得不从您提供的答案中删除()
。 - Rorrim<form data-before-submit="MyObject.myMethod">
<button type="submit">Submit</button>
</form>
$('form').on('submit', function(e){
var beforeSubmit = $(this).attr('data-before-submit');
if( beforeSubmit ){
params = beforeSubmit.split(".");
objectName = params[0];
methodName = params[1];
result = window[objectName][methodName]($(this));
if( result !== true ){
e.preventDefault();
}
}
});
var MyObject = {
myMethod: function(form){
console.log('worked');
return true;
}
};
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FooClass'
,还有其他人遇到吗?需要翻译为中文。 - Anand Rockzz