原型中的in和hasOwnProperty

1,403 阅读1分钟

1.hasOwnProperty():

hasOwnProperty可以检测一个属性是存在于实例中,还是原型中。返回布尔值,只有当属性存在于实例中的时候才会返回true

function Person(){}
			
Person.prototype.name = 'hello';

var p = new Person();

console.log(p.hasOwnProperty('name')) 		//false

p.name = 'world';
			
console.log(p.hasOwnProperty('name'))		//true

delete p.name;
						
console.log(p.hasOwnProperty('name'))		//false

2.in

有两种方式使用in,常用的是for-in(遍历所有能通过对象访问的,可枚举的属性,包括实例属性和原型属性,具体可见另一篇文章Javascript对象属性的枚举方法比较),而单独使用则能判断对象是否存在某个属性,不论这个属性是存在于实例中还是原型中。

function Person(){}
			
Person.prototype.name = 'hello';

var p = new Person();

console.log('name' in p);		//true

p.name = 'world';

console.log('name' in p);		//true
			

我们同时使用in和hasOwnProperty,可以判断属性是不是存在于原型中。

如果该属性是原型中的属性,则返回true,否则是false

function Person(){}
			
Person.prototype.name = 'hello';

var p = new Person();
			
function isOwnProperty(obj,prop){
	return !obj.hasOwnProperty(prop)&&(prop in obj);
}

isOwnProperty(p,'name') 		//true

p.name = 'world';

isOwnProperty(p,'name') 		//false