【问题标题】:How to prevent a method call, when that's not exist [duplicate]当方法调用不存在时如何防止方法调用[重复]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您几乎明白了,只需要在检查typeof 您的财产时稍作修改。 typeof 返回一个字符串,表示该对象的类型。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-26
      • 2017-02-27
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2015-02-17
      相关资源
      最近更新 更多