js原型对象的性质(二):原型与in操作符

原型与in操作符

1.单独使用in操作符:

通过对象能够访问给定属性时返回true,无论该属性存在于实例中还是原型中。

function Person(){
}

Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="SoftWare Engineer";
Person.prototype.sayName=function(){
    console.log(this.name);
};
var person1=new Person();
var person2=new Person();
console.log(person1.hasOwnProperty("name"));//false
console.log("name" in person1);//true
person1.name="yyq";
console.log(person1.hasOwnProperty("name"));//true
console.log("name" in person1);//true

2.通过in操作符确定是否是原型的属性

function hasPrototypeProperty(object,name){
	return !object.hasOwnProperty(name)&&(name in object);
}
person1.name="yyq";
console.log(hasPrototypeProperty(person1,"name"));//false
console.log(hasPrototypeProperty(person2,"name"));//true

3.for-in循环

返回的是所有能够通过对象访问的、可枚举的属性,其中既包括存在于原型中的属性,也包括存在于实例中的属性。屏蔽了原型中不可枚举属性的实例属性也会在for-in循环中返回。因为根据规定,所有开发人员定义的属性都是可枚举的。

person1.hobby="painting";
for(var prop in person1){
    console.log(person1[prop]);
}
/*
painting
Nicholas
29
SoftWare Engineer
[Function]
*/
var o={
	toString:function(){
		return "my Object";
	}
};
for(var prop in o){
	console.log(o[prop]);//[Function: toString]
}

4.替代for-in的两个方法

要取得对象上所有可枚举的实例属性,可以使用ECMAScript5的Object.keys()方法。这个方法接收一个对象作为参数,返回一个包含所有可枚举属性的字符串数组。

var keys=Object.keys(Person.prototype);
console.log(keys);//[ 'name', 'age', 'job', 'sayName' ]
person1.name="Greg";
person1.age="15";
var p1keys=Object.keys(person1);
console.log(p1keys);//[ 'name', 'age' ]

如果想要得到所有实例属性,无论它是否可枚举,都可以使用Object.getOwnPropertyNames()方法。

var keys=Object.getOwnPropertyNames(Person.prototype);
console.log(keys);//[ 'constructor', 'name', 'age', 'job', 'sayName' ]
person1.name="Greg";
person1.age="15";
var p1keys=Object.getOwnPropertyNames(person1);
console.log(p1keys);//[ 'name', 'age' ]

5.默认不可枚举的属性和方法

hasOwnProperty()、propertyIsEnumerable()、toLocalString()、toString()和valueOf()

猜你喜欢

转载自blog.csdn.net/yangyuqingabc/article/details/82953433