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

Javascript 当方法调用不存在时,如何防止方法调用,javascript,jquery,Javascript,Jquery,在我的objectinit中,我用名称调用方法。但有时,这些方法可能没有声明,或者我不想调用它们。在这种情况下,如何防止调用我的方法 以下是我的调用方法:此[collectionName];-这里的名称是我收到的参数。因此,该方法是在对象中声明的 以下是完整代码: init: function( collectionName, size ){ if( (typeof this[collectionName] ) === undefined ) return; //but

在我的objectinit中,我用名称调用方法。但有时,这些方法可能没有声明,或者我不想调用它们。在这种情况下,如何防止调用我的方法

以下是我的调用方法:此[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

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

// it must be === "undefined" (in quotes) actually, not === undefined
if( (typeof this[collectionName] ) === "undefined" ) return; 
然而,正如错误中提到的,问题是

此[collectionName]不是函数

i、 e.此[collectionName]确实存在,但它不是一个函数,因此您无法调用它

您可以更改函数以确保此[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();
}
if (typeof this[collectionName] !== 'function') return;

你就快拿到了,只需要在检查你的财产类型时稍加修改。typeof返回指示该对象类型的字符串

if( (typeof this[collectionName] ) === 'undefined' ) return;
// notice how I made 'undefined' into a string
虽然我认为如果您检查它是否不是一个函数会更好:

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();
}
if (typeof this[collectionName] !== 'function') return;

您可以检查此[collectionName]exista,如果此[collectionName]==函数的类型为,则此[collectionName]exista是一个函数?最好检查此[collectionName]==函数的类型这是我编写的条件,但不适用于我。看到我的命令了吗