【发布时间】:2017-08-31 23:39:37
【问题描述】:
在我的对象初始化中,我用它们的名字调用方法。但有时,这些方法可能没有声明或者我不想调用它们。如果有这种机会,如何防止我的方法被调用?
这是我的调用方法:this[collectionName](); - 这里的名称是我收到的参数。所以方法是在对象中声明的。
这里是完整的代码:
init: function( collectionName, size ){
if( (typeof this[collectionName] ) === undefined ) return; //but not works!!!
this.collectionName = collectionName;
this.size = size.toUpperCase() == "SMALL" ? 20 : size.toUpperCase() == "MEDIUM" ? 35 : lsize.toUpperCase() == "LARGE" ? 50 : "SMALL";
this[collectionName]();//some time method will not exist. how to check the existence and prevent it from call?
return this.generateRecords();
}
当方法不是他们的 then 时我收到错误:
New-DataModels.js?bust=1491457640410:69 Uncaught TypeError: this[collectionName] is not a function
【问题讨论】:
-
你可以检查
this[collectionName]存在并且是一个函数 -
if (typeof this[collectionName] === "function") ?
-
更好地检查 (typeof this[collectionName] === "function")
-
这就是我写的条件,但对我不起作用。看我的评论
标签: javascript jquery