Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript hasOwnProperty and prototype

Tags:

javascript

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?

like image 970
shellyan Avatar asked Nov 08 '13 04:11

shellyan


People also ask

What is hasOwnProperty JavaScript?

hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Should I use hasOwnProperty?

In general, hasOwnProperty() is the right choice most of the time, because you avoid issues with special keys, like constructor . A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() .

What is prototype in es6?

The prototype property allows you to add properties and methods to any object (Number, Boolean, String and Date, etc.). Note − Prototype is a global property which is available with almost all the objects. Use the following syntax to create a Boolean prototype.

How do you check if an object contains a key in JavaScript?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.


1 Answers

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
like image 75
icktoofay Avatar answered Sep 24 '22 02:09

icktoofay