【JavaScript】面向对象:hasOwnProperty()方法与in操作符

hasOwnProperty()方法

使用 hasOwnProperty()方法(是从 Object 继承来的)可以检测一个属性是存在于实例中,还是存在于原型中。只在给定属性存在于对象实例中时,才会返回 true。

function Person(){ 
} 
Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer"; 
Person.prototype.sayName = function(){
	alert(this.name); 
}; 
var person1 = new Person(); 
var person2 = new Person(); 
console.log(person1.hasOwnProperty("name")); //false 
person1.name = "Greg"; 
console.log(person1.name); //"Greg"——来自实例
console.log(person1.hasOwnProperty("name")); //true 
console.log(person2.name); //"Nicholas"——来自原型
console.log(person2.hasOwnProperty("name")); //false 
delete person1.name; 
console.log(person1.name); //"Nicholas"——来自原型
console.log(person1.hasOwnProperty("name")); //false  

in操作符

in 操作符:单独使用或者在for-in 循环中使用。单独使用时,in 操作符会在通过对象能够访问给定属性时返回 true,无论该属性存在于实例中还是原型中。

function Person(){ 
} 
Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer"; 
Person.prototype.sayName = function(){ 
	alert(this.name); 
}; 
var person1 = new Person(); 
var person2 = new Person(); 
console.log(person1.hasOwnProperty("name")); //false 
console.log("name" in person1); //true 
person1.name = "Greg"; 
console.log(person1.name); //"Greg" ——来自实例
console.log(person1.hasOwnProperty("name")); //true 
console.log("name" in person1); //true 
console.log(person2.name); //"Nicholas" ——来自原型
console.log(person2.hasOwnProperty("name")); //false 
console.log("name" in person2); //true 
delete person1.name; 
console.log(person1.name); //"Nicholas" ——来自原型
console.log(person1.hasOwnProperty("name")); //false 
console.log("name" in person1); //true 

不论属性存在于实例中还是存在于原型中,调用"name" in person1 始终都返回 true

发布了10 篇原创文章 · 获赞 1 · 访问量 295

猜你喜欢

转载自blog.csdn.net/AAABingBing/article/details/104221244