1

Here i created an instance of parent class and defined a property called smile on the object itself. I know that the property defined on constructor's prototype is not the object's own property .But how come "smile" property have not passed the hasOwnProperty test inside for in loop?

function Parent(){
   this.name='parent';
}
Parent.prototype.age='34';

var p=new Parent();
p.smile='nice';  // not an own property ?
console.log(p);
for(var prop in p){
  if(Object.hasOwnProperty(prop)){
       console.log(prop);  // prints only "name"
   }
}
AL-zami
  • 8,902
  • 15
  • 71
  • 130

2 Answers2

5

You're misusing Object.prototype.hasOwnProperty(). The said function is to be called with the tested object as its context, which means you should do p.hasOwnProperty(prop) instead of Object.hasOwnProperty(prop). Then you would get the result you are expecting.

hasOwnProperty is defined on Object.prototype, which means that most objects (with the exception of those for which you have manually set the prototype to null) will inherit the method so it can be invoked on them. p is such an object. There is nothing unusual about its prototype chain, so it should work when changed according to the above description.

Now you might ask why your code doesn't throw an error on the if statement line. That's because Object is a function and, as such, ultimately inherits from Object.prototype.

rhino
  • 13,543
  • 9
  • 37
  • 39
4
if (Object.hasOwnProperty(prop)) {

Checks if Object as an own property of the given name. Object.name exists on the Object function, which is why it returns true.

What you want is p.hasOwnProperty(prop) so that you're checking if the instance itself has the property rather than inheriting from the prototype. However, calling the function in this manner will cause issues if the instance has an own property named hasOwnProperty, so it's common to see the expanded form of:

Object.prototype.hasOwnProperty.call(p, prop)
zzzzBov
  • 174,988
  • 54
  • 320
  • 367