hasOwnProperty()方法
确定某个对象是否具有带指定名称的属性。
语法
object.hasOwnProperty(proName)
参数
object
必需。对象的实例。
proName
必需。一个属性名称的字符串值。
使用hasOwnProperty()方法可以检测一个属性是存在于实例中,还是存在于原型中。这个方法只在给定属性存在于对象实例中时,才会返回true。
结合之前讲的代码实例,我们再来看一下hasOwnProperty()方法的使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function Person(){
}
Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="software Engineer";
Person.prototype.sayName=function(){
return this.name;
}
var person1=new Person();
var person2=new Person();
document.write(person1.hasOwnProperty("name"));
document.write("<br>");
document.write("name" in person1);
</body>
</html>
output:
false
true
上面代码中我顺道也写出来了in操作符的结果,下面我们来讲讲in操作符。
in操作符会在通过对象能够访问给定属性时返回true,无论属性存在于实例中还是原型中。
在《javascript高级程序设计》中为了确定属性到底是存在原型中还是存在于实例中。书中同时用到了hasOwnProperty()方法与in操作符,并且写出了一个函数,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function hasPrototypeProperty(object,name){
return !object.hasOwnProperty(name) && (name in object);
}
function Person(){
}
Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="software Engineer";
Person.prototype.sayName=function(){
return this.name;
}
var person1=new Person();
var person2=new Person();
document.write(person1.hasOwnProperty("name"));
document.write("<br>");
document.write("name" in person1);
document.write("<br>");
document.write(hasPrototypeProperty(person1,"name"));
document.write("<br>");
person1.name="xiaohong";
document.write(hasPrototypeProperty(person1,"name"));
</script>
</body>
</html>
output:
false
true
true
false