对象属性的遍历

Object.keys能够得到自身可枚举的属性,但得不到原型链上的属性,得不到Symbol属性

Object.getOwnPropertyNames能够得到自身的属性,包括不可枚举的,但得不到原型链上的属性,得不到Symbol属性

Object.getOwnPropertySymbols得到自身的Symbols属性,包括不可枚举的

for ...in 得到自身和原原型链上的可枚举属性

'use stric';
class A {
	constructor(){
		this.name = 'Jack';
	}
	
	getName(){
		
	}
}
 class B extends A{
 	constructor(){
 		super();
 		this.age = 18;
 	}
 	
 	getAge(){
 		
 	}
 	
 	[Symbol('fullname')](){
 		
 	}
 }
 B.prototype.getClass = function(){
 	
 }
var b = new B();
//Object.keys能够得到自身可枚举的属性,但得不到原型链上的属性
//得不到Symbol属性
console.log(Object.keys(b));//[ 'name', 'age' ]
console.log(Object.keys(B.prototype));//[ 'getClass' ]



//Object.getOwnPropertyNames能够得到自身的属性,包括不可枚举的,
//但得不到原型链上的属性
//得不到Symbol属性
console.log(Object.getOwnPropertyNames(b));//[ 'name', 'age' ]
console.log(Object.getOwnPropertyNames(B.prototype));//[ 'constructor', 'getAge', 'getClass' ]

//Object.getOwnPropertySymbols得到自身的Symbols属性,包括不可枚举的
console.log(Object.getOwnPropertySymbols(B.prototype));//[ Symbol(fullname) ]


//for ...in 得到自身和原原型链上的可枚举属性
//通过class语法糖创建的属性和方法是不可枚举的
for(let item in b){
	console.log(item);//name age getClass
}

//通过class语法糖创建的属性和方法是不可枚举的
//通过B.prototype方式添加的属性和方法可枚举
console.log(Object.getOwnPropertyDescriptor(B.prototype,'getAge'));
//{ value: [Function: getAge],
//writable: true,
//enumerable: false,
//configurable: true }


console.log(Object.getOwnPropertyDescriptor(B.prototype,'getClass'));
//{ value: [Function],
//writable: true,
//enumerable: true,
//configurable: true }

如果想要访问自身可枚举的属性:将for ...in  和 Object.getOwnPropertyNames一起使用

//name age 是自身可枚举属性,getClass是原型链上的可枚举属性

for(let item in b){
	console.log(item);//name age getClass
}


for(let item in b){
	//此时item包含自身和原型链上的可枚举属性
	if(Object.getOwnPropertyNames(b).indexOf(item) !== -1){
		console.log(item)//name age
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值