[英]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.