javascript hasOwnProperty和原型 [英] javascript hasOwnProperty and prototype

查看:48
本文介绍了javascript hasOwnProperty和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?谁能解释?

推荐答案

JavaScript正在寻找属性时,它首先会检查对象本身.如果不存在,它通常会沿着原型链继续前进. hasOwnProperty 的存在是为了仅检查对象本身,不明确地沿着原型链前进.如果要检查属性是否存在,请检查原型链中的所有内容,请使用 in 运算符:

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

这篇关于javascript hasOwnProperty和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆