2017-04-06 46 views
2

在我的对象init中,我用他们的名字调用方法。但有些时候,这些方法可能没有声明,或者我不想给它们打电话。如果有机会,如何防止我的方法被调用?如何防止方法调用,当不存在

这里是我的调用方法: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(); 

     } 

我得到一个错误,当该方法是不是他们那么:

New-DataModels.js?bust=1491457640410:69 Uncaught TypeError: this[collectionName] is not a function 
+0

您可以检查'这个[集合名]'exista,如果是一个函数 – Satpal

+0

(typeof运算这个[集合名] ===“功能”)? –

+0

这就是我写的一个条件,但不适合我。查看我的commet – 3gwebtrain

回答

2

一个变量确实存在,并声明,因为它不会进入功能,如果它没有因为这样存在:

// it must be === "undefined" (in quotes) actually, not === undefined 
if((typeof this[collectionName]) === "undefined") return; 

然而,在错误mentionted的proble M为

this[collectionName]不是一个函数

this[collectionName]确实存在,但它不是一个功能,因此你不能调用它。

你可以改变你的功能,以确保this[collectionName]是一个函数:

init: function(collectionName, size){ 
    if (typeof this[collectionName] !== 'function') return; 

    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(); 
} 
2

你几乎得到了它,只需要在检查typeof自己财产的小改款。 typeof返回一个字符串,指示该对象的类型。

if((typeof this[collectionName]) === 'undefined') return; 
// notice how I made 'undefined' into a string 

虽然我认为这将是更好,如果你检查,如果它不是一个功能:

if (typeof this[collectionName] !== 'function') return; 
相关问题