我有几个对象,它们都有一些调用相同但执行不同操作的方法。
When I click a button, I want to call the
init()
method, but the object is different based on what button I clicked.
这是一个片段
$btn.on('click', function(e){
e.preventDefault();
var $trigger = $(this);
var objectName = $trigger.data('object');
/*
if objectName is 'user', I want to call user.init(),
if it's 'product' I want to call product.init() and so on...
right now i get an error if I call like his
*/
objectName.init($trigger);
});
是否可以动态调用这样的对象?我知道这是因为它的属性和方法,但我没有找到任何有关此问题的信息。
谢谢。
最佳答案
最好做映射
var entities = {
user: user,
entity: entity
}
var objectName = $trigger.data('object');
entities[objectName].init($trigger);
关于javascript - jQuery:使用基于变量值的动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38996674/