[英]Javascript dynamically invoke object method from string
Can I dynamically call an object method having the method name as a string?我可以动态调用具有方法名称作为字符串的对象方法吗? I would imagine it like this:
我会想象它是这样的:
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]();
Properties of objects can be accessed through the array notation:可以通过数组符号访问对象的属性:
var method = "smile";
foo[method](); // will execute the method "smile"
When we call a function inside an object, we need provide the name of the function as a String.当我们在对象内部调用函数时,我们需要以字符串形式提供函数的名称。
var obj = {talk: function(){ console.log('Hi') }};
obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
method can be call with eval eval("foo." + method + "()");
方法可以用 eval
eval("foo." + method + "()");
调用eval("foo." + method + "()");
might not be very good way.可能不是很好的方法。
I would like to leave an example here for this.我想在这里留下一个例子。 For example;
例如; i want to call a dynamically check method while submitting the form.
我想在提交表单时调用动态检查方法。
<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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.