如何防止方法调用,当它不存在时

时间:2017-04-06 05:52:34

标签: javascript jquery

在我的对象init中,我用他们的名字调用方法。但有一段时间,这些方法可能没有声明,或者我不想调用它们。如果有这种机会,如何防止我的方法被召唤?

这是我的调用方法:this[collectionName](); - 此处的名称是我收到的参数。所以该方法在object中声明。

这里是完整代码:

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

2 个答案:

答案 0 :(得分:2)

变量确实存在并被声明,因为如果它不存在则不会进入函数:

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

然而,正如错误提到的,问题在于

  

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

答案 1 :(得分:2)

你几乎得到它,只需要一点点修改就可以检查typeof你的财产。 typeof返回一个字符串,指示该对象的类型。

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

虽然我认为如果检查它不是一个函数会更好:

if (typeof this[collectionName] !== 'function') return;