我可以动态调用以方法名称为字符串的对象方法吗?我会这样想:
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();
Answers:
如果属性名称存储在变量中,请使用 []
foo[method]();
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FooClass'
别人收到这个丑陋的错误吗?
可以通过数组符号访问对象的属性:
var method = "smile";
foo[method](); // will execute the method "smile"
当我们在对象内部调用函数时,我们需要以String的形式提供函数的名称。
var obj = {talk: function(){ console.log('Hi') }};
obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
我想在这里留下一个例子。例如; 我想在提交表单时调用动态检查方法。
<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;
}
};