我是靠谱客的博主 温柔长颈鹿,这篇文章主要介绍Js中获取对象属性的几种方法解析for-in枚举 Object.keys() Object.getOwnPropertyNames(),现在分享给大家,希望可以做个参考。

for-in枚举

在使用for-in循环时,返回的是所有能够通过对象访问的、可枚举的属性,其中既包括存在于实例中的属性,也包括存在于原型中的属性,屏蔽了原型中不可枚举属性的实例属性也会在for-in循环中返回。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript"> function Person(name, sex) { this.name = name; this.sex = sex; this.getName=1; } Person.prototype.getName = function() { return this.name; } Person.prototype.getSex = function() { return this.sex; } Object.prototype.age=1; var obj = new Person("Tom", 0); for(var prop in obj) { console.log(prop);// name sex getName(虽然在实例本身及原型链 //中均有出现,但只遍历一次,及此循环只循环了5次) getSex age } for(var i in [1,2,3]){ console.log(i);//0 1 2 age } </script>

 Object.keys()

 Object.keys()获取的是对象实例本身的可枚举属性,不包括原型中的属性。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script type="text/javascript"> function Person(name, sex) { this.name = name; this.sex = sex; this.getName=1; } Person.prototype.getName = function() { return this.name; } Person.prototype.getSex = function() { this.getSex=2; return this.sex; } Object.prototype.age=1; var obj = new Person("Tom", 0); var objProps=Object.keys(obj); console.log(objProps);//["name", "sex", "getName"] var objPrototypeProps=Object.keys(obj.__proto__); console.log(objPrototypeProps);//["getName", "getSex"] </script>

 Object.getOwnPropertyNames()

Object.getOwnPropertyNames()获取的是对象本身的所有属性(不包括原型的属性),既包括可枚举属性,也包括不可枚举属性。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script type="text/javascript"> function Person(name, sex) { this.name = name; this.sex = sex; this.getName=1; } Person.prototype.getName = function() { return this.name; } Person.prototype.getSex = function() { this.getSex=2; return this.sex; } var objPrototypeAllProps=Object.getOwnPropertyNames(Person.prototype); console.log(objPrototypeAllProps);//["constructor", "getName", "getSex"], //constructor为不可枚举属性,也被获取到 </script>

 

最后

以上就是温柔长颈鹿最近收集整理的关于Js中获取对象属性的几种方法解析for-in枚举 Object.keys() Object.getOwnPropertyNames()的全部内容,更多相关Js中获取对象属性内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部