4

In my JavaScript code I have a function which contains following set of statements

function someFunc(object,action){
                    for(var property in object){
                        if(Object.prototype.hasOwnProperty.call(object, property)){
                            //TODO
                        }
                    }
                }
}

and If I replace if statement inside function with

if(obj.hasOwnProperty(property)){
    //TODO
    }

both are working fine for me. All I want to know is that which among them is better approach and why? I know that obj.hasOwnProperty(property) check for the personal property of the object. I also want to know how call is chaining up here

object.prototype.hasOwnProperty.call(object, property)

Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55
  • If the object for this or that reason hasn't got a way to access Object.prototype (normally all objects have) you might choose use the first method. – Redu May 05 '16 at 09:40

1 Answers1

7

I would generally always go with obj.hasOwnProperty(prop).

There's less indirection and it'll be much clearer for others trying to read and understand your code. It'll also run slightly faster, because you don't need to rebind the context for this.

I can't think of many pitfalls that would require you to use the other approach.

  • If obj inherits from null not Object.prototype
  • If hasOwnProperty has been redeclared on obj
  • If hasOwnProperty has been redeclared in obj's prototype chain

All of these scenarios are pretty rare in day to day applications and if you do find one of them, it's safest, easiest and best to fix the problem there, rather than use the more defensive Object.prototype.hasOwnProperty.call form.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120