在看书籍的时候看到了关于获取对象属性的集中方式,下面给一一的介绍一下:
var Person = function () { this.class='ddd'; }; var pp=function(){}; Person.prototype.name = 'tlc'; Person.prototype.age = '25'; Person.prototype.sex = 'boy'; Person.prototype.sayInfo = function () { console.info(this.name + "--" + this.age + "--" + this.sex) }; var person1 = new Person(); var person2 = new Person();
object.hasOwnProperty():用于判断当前对象是否包含某一个属性,但是却把原型链对象上的属性给过滤掉
console.log(person1.hasOwnProperty('class'));//true 因为Person中有这个属性 console.info(person1.hasOwnProperty('name'));//false 因为name属性在原型连对像上
for...in:这个循环会遍历当前对象的所有可枚举,可访问的属性,也包含此对象的原型链上对象的所有可枚举属性
for(var prop in person1){ console.log(prop);//class,name.age,sex,sayInfo }但是不会返回toString,toLocalString...等函数,这是因为js给定义成了不可枚举的属性
in:单独使用的时候会返回true或者false,这个是判断属性是否是在通过对象能够访问的属性时返回true,不论是原型链上的属性还是对象上的属性
console.log('name' in person1);//true console.log('class' in person1);//true console.log('pp' in person1);//false
console.log('toString' in person1);//true
object.keys():这个函数返回的是当前对象可枚举的属性,并不包含原型连对象上的属性
person1.teacher='xjp'; var keys1=Object.keys(Person.prototype); console.log(keys1);//name,age,sex,sayInfo var keys2=Object.keys(person1); console.info(keys2);//class,toString,teacher
Object.getOwnPropertyNames():返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性)组成的数组
var attrs=Object.getOwnPropertyNames(Person.prototype); console.log(attrs);//constructor,name,age,sex,sayInfoObject.getOwnPropertyDescriptor() 返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
var attrs1=Object.getOwnPropertyDescriptor(person1,'class'); console.log(attrs1);//Object {value: "ddd", writable: true, enumerable: true, configurable: true}