检查对象属性和调用方法的更好方法

时间:2021-10-14 21:31:47

(Sorry if it was queried previously, I didnt found it)

(对不起,如果以前查询过,我没找到它)

I used to check if an object and method exists and call it in this way:

我曾经检查过对象和方法是否存在并以这种方式调用它:

 obj && obj.method && obj.method()

But, I suspect that some cases this are making some troubles on IE..

但是,我怀疑有些情况下这会给IE带来一些麻烦..

Do I need check it using typeof undefined/function/object ?

我需要使用typeof undefined / function / object进行检查吗?

 typeof obj === 'object' && typeof obj.method === 'function' && obj.method()

I would like to know what is the securest and clearest style to code it.

我想知道什么是最安全和最清晰的代码风格。

1 个解决方案

#1


5  

To ensure that you can properly execute a method named method on an object named object, this is the shortest safe check:

为了确保您可以在名为object的对象上正确执行名为method的方法,这是最短的安全检查:

if (typeof object === 'object' && typeof object.method === 'function') {
    object.method();
}

You need to first check that the object exists, then make sure that the property you want is a function. Any other checks are redundant.

您需要先检查对象是否存在,然后确保所需的属性是一个函数。任何其他检查都是多余的。

Note this falls apart if you have something weird like a number 0 or boolean false with a method property you're trying to execute, but you may have larger problems if you're appending properties to booleans and numbers.

请注意,如果您有一些奇怪的东西,如数字0或布尔值假,并且您尝试执行的方法属性,但如果您将属性附加到布尔值和数字,则可能会遇到更大的问题。

#1


5  

To ensure that you can properly execute a method named method on an object named object, this is the shortest safe check:

为了确保您可以在名为object的对象上正确执行名为method的方法,这是最短的安全检查:

if (typeof object === 'object' && typeof object.method === 'function') {
    object.method();
}

You need to first check that the object exists, then make sure that the property you want is a function. Any other checks are redundant.

您需要先检查对象是否存在,然后确保所需的属性是一个函数。任何其他检查都是多余的。

Note this falls apart if you have something weird like a number 0 or boolean false with a method property you're trying to execute, but you may have larger problems if you're appending properties to booleans and numbers.

请注意,如果您有一些奇怪的东西,如数字0或布尔值假,并且您尝试执行的方法属性,但如果您将属性附加到布尔值和数字,则可能会遇到更大的问题。