简体   繁体   English

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

[英]Better way to check object property and call a method

(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. 我想知道什么是最安全和最清晰的代码风格。

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或布尔值false ,并且您尝试执行的method属性,但如果您将属性附加到布尔值和数字,则可能会遇到更大的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 设置嵌套对象属性的更好方法? - Better way to set a nested object property? 在ExtJS中调用超类方法的更好方法 - Better way to call superclass method in ExtJS 调用阴影原型方法的更简单/更好的方法? - Simpler / better way to call shadowed prototype method? 检查嵌套 object 数组的更好方法是什么 - What is the better way to check in array of nested object 通过属性动态调用 object 中的方法 - Call method in object by property dynamically 有没有更好的方法来调用 .env 文件是否存在检查赛普拉斯中的 function? - Is there a better way to call a .env file exists check function in cypress? 这是检查对象是否具有属性的最佳方法 - Which is the best way to check if an object has property 如何在JS中以更好的方式有条件地更改对象属性值? - How to conditionally change object property value in the better way then this solution in JS? 如何使用窗口对象(或更好的方法)制作动态属性名称 - how to use the window object (or better way) to make dynamic property names 单击时将新属性添加到另一个 function 中的现有 object 的更好方法 - better way to add new property to existing object in another function on click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM