3

(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..

Do I need check it using 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.

Martin Borthiry
  • 5,256
  • 10
  • 42
  • 59

1 Answers1

5

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

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.

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • If `object` is not defined, it will raise a `ReferenceError` exception. – VisioN Jan 07 '13 at 18:31
  • Now it has nothing different with the OP's solution :) – VisioN Jan 07 '13 at 18:33
  • if object is not defined why is not evaluated as false? what is the difference again var object = object || {}; ? – Martin Borthiry Jan 07 '13 at 20:45
  • 1
    @MartinBorthiry there's a difference between *being undefined* (which will throw an exception if you put it in an `if` statement, which the edit protects against) and *having the value undefined* (which evaluates to `false` in an `if` statement). – jbabey Jan 07 '13 at 20:47