Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

javascript hasOwnProperty and prototype

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...