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??有谁能解释一下吗?
发布于 2013-11-08 12:21:31
当JavaScript查找属性时,它首先查找对象本身。如果它不在那里,它通常会一直沿着原型链向上移动。hasOwnProperty的存在只是为了检查对象本身,而不是显式地沿着原型链进行遍历。如果您想检查某个属性是否存在,检查原型链中的所有内容,请使用in运算符:
'sayName' in penguin // => true发布于 2013-11-08 12:22:58
因为hasOwnProperty检查属性本身是否存在,而不是作为继承的one form原型,所以read this
此方法可用于确定对象是否具有指定的属性作为该对象的直接属性;与in运算符不同,此方法不检查对象的原型链。
发布于 2013-11-08 12:24:59
因为'sayname‘是从'Animal’继承的,而不是'penguin‘自己的属性。
类似的例子:
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.https://stackoverflow.com/questions/19851511
复制相似问题