相同点
function Person(name){
this.name = name;
}
Person.prototype = {
age:18,
sayName: function () {
console.log(this.name)
}
}
let person1 = new Person('litao');
console.log(Object.getOwnPropertyNames(person1)) //['name']
console.log(Object.keys(person1)) //['name']
const _item = Symbol('item')
const myobject = {
name: 'Saku',
age: '21',
[_item]: 'mysymbol',
say() {
console.log("Hello,world")
}
}
console.log(Object.getOwnPropertyNames(myobject));// ["name", "age", "say"]
console.log(Object.keys(myobject)) //['name', 'age', 'say']
不同点
- 对于数组,
Object.getOwnPropertyNames()
包含一个名为 length
的属性,Object.keys()
没有
const animals = ['dog', 'cat', 'tiger']
Object.keys(animals) // ['0', '1', '2']
Object.getOwnPropertyNames(animals) // ['0', '1', '2', 'length']
-
Object.getOwnPropertyNames(obj)
返回对象 obj 的所有属性(包括可枚举和不可枚举),而Object.keys(obj)
返回所有可枚举的属性。
const screen = {
width: 1200,
height: 800
}
Object.defineProperty(screen, 'resolution',{
value: '2560 x 1440',
enumerable: false //不可枚举
})
console.log(Object.getOwnPropertyNames(screen)) // ['width', 'height', 'resolution']
console.log(Object.keys(screen)) // ['width', 'height']
网友评论