5
function Animal(name,numLegs){
this.name = name;
this.numLegs = numLegs}

Animal.prototype.sayName = function(){
console.log("Hi my name is " + this.name );}

var penguin = new Animal("Captain Cook", 2);
  penguin.sayName();
for (var prop in penguin){
console.log(prop);}
penguin.hasOwnProperty('sayName')

result:

name
numLegs
sayName
=> false

I dont know why hasOwnProperty return false?? can anyone explain?

shellyan
  • 51
  • 1
  • 2

3 Answers3

17

When JavaScript is looking for a property, it first looks into the object itself. If it isn't there, it normally keeps walking up the prototype chain. hasOwnProperty exists to check only the object itself, explicitly not walking up the prototype chain. If you want to check if a property exists at all, checking everything in the prototype chain, use the in operator:

'sayName' in penguin  // => true
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • Just for info, [*propertyIsEnumerable*](http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.7) doesn't go along the `[[Prototype]]` chain either. – RobG Nov 08 '13 at 04:32
  • Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain. – shellyan Nov 08 '13 at 04:38
1

Because hasOwnProperty check the property is present or not in itself, not as an inherited one form prototypes, read this

This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
0

Because 'sayname' is inherited from 'Animal' its not 'penguin' own property.

check : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

similar example :

function Foo() {
  this.value = 'qwert';
}
Foo.prototype.say = "hello";

var foo = new Foo();

foo.hasOwnProperty("say"); // False, since say is inherited from the prototype object.
foo.hasOwnProperty("value"); // True, since value is the property of foo itself.
Ankit Tyagi
  • 2,381
  • 10
  • 19