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

结果:

name
numLegs
sayName
=> false

我不知道为什么 hasOwnProperty 返回 false?谁能解释一下?

4

3 回答 3

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
于 2013-11-08T04:21:30.727 回答
1

因为 hasOwnProperty 检查属性本身是否存在,而不是作为继承的一种形式原型,请阅读此

该方法可用于判断一个对象是否具有指定属性作为该对象的直接属性;与 in 运算符不同,此方法不检查对象的原型链。

于 2013-11-08T04:22:58.007 回答
0

因为“sayname”是从“Animal”继承的,它不是“penguin”自己的属性。

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

类似的例子:

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.
于 2013-11-08T04:24:59.090 回答