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

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 に答える