最近面試遇到問如何獲取對象全部屬性名的方法,總結一下:
對象屬性類型分類:
1.ESMAScript分類
數據類型 又分為可枚舉和不可枚舉類型
訪問器類型
2.上下文分類
原型屬性
實例屬性
1.列舉自身但不包括原型的可枚舉屬性名 Object.keys(obj)
// 遍歷對象
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.demo = function() {};
let cj = new Person('cj', 25);
// 通過Object.defineProperty定義一個不可枚舉屬性
Object.defineProperty(cj, 'weight', {
enumerable:false
})
// enumerable = true
// console.log(Object.keys(cj)) // name age
// enumerable = false
// console.log(Object.keys(cj)) // name age weight
2.列舉包括自身不可枚舉但不包括原型的屬性名 Object.getOwnPropertyNames(obj)
function Person(name, age) {
this.name = name;
this.age = age;
}
// 設置原型屬性
Person.prototype.demo = function() {};
let cj = new Person('cj', 25);
// 通過Object.defineProperty定義一個不可枚舉屬性
Object.defineProperty(cj, 'weight', {
enumerable:false
})
// 獲取屬性名
console.log(Object.getOwnPropertyNames(cj)) // name age weight
3.獲取自身和原型鏈上的可枚舉屬性 for in 返回的順序可能與定義順序不一致
function Person(name, age) {
this.name = name;
this.age = age;
}
// 設置原型屬性
Person.prototype.demo = function() {};
Object.prototype.j = 1
let cj = new Person('cj', 25);
// 通過Object.defineProperty定義一個不可枚舉屬性
Object.defineProperty(cj, 'weight', {
enumerable:false
})
let props = []
for(prop in cj){
props.push(prop)
}
console.log(props) //name age weight j
4.獲取自身Symbol屬性 Object.getOwnPropertySymbols(obj)
let obj = {};
// 為對象本身添加Symbol屬性名
let a = Symbol("a");
obj[a] = "localSymbol";
// 為對象原型添加Symbol屬性名
let b = Symbol("b")
Object.prototype[b] = 111
let objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols); //Symbol(a)
5.獲取自身包括不可枚舉和Symbol屬性名,但不包括原型 Reflect.ownKeys(obj)
// 遍歷對象
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.demo = function() {};
let s = Symbol('s')
let cj = new Person('cj', 25);
// 通過Object.defineProperty定義一個不可枚舉屬性
Object.defineProperty(cj, 'weight', {
enumerable: false
})
cj[s] = 1
let a = Symbol('a')
Object.prototype[a] = 1
console.log(Object.getOwnPropertyNames(cj)) //name age weight
console.log(Reflect.ownKeys(cj)) //name age weight Symbol(s)