Search code examples
javascriptclassoophasownproperty

why property defined after object's instantiation is not an own property


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"
   }
}

Solution

  • 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)