理解对象
创建对象
Object 实例
var person = new Object()
person.name = "ChangLau"
person.age = 29
person.job = "SoftWare Engineer"
person.sayName = function(){
console.log(this.name)
}
对象字面量
var person = {
name: "ChangLau",
age: 29,
job: "SoftWare Engineer",
sayName: function(){
console.log(this.name)
}
}
属性类型
数据属性
- [[Configurable]] 表示是否能够通过 delete 删除属性从而重新定义属性,能否修改属性的特性,或者能否把属性修改为访问器属性
- [[Enumerable]] 表示能否通过 for-in 循环返回属性
- [[Writable]] 表示能否修改属性的值
- [[Value]] 包含这个属性的数据值
var person = {
name: "ChangLau",
age: 29,
job: "SoftWare Engineer",
sayName: function(){
console.log(this.name)
}
}
Object.getOwnPropertyDescriptors(person)
// age:
// configurable: true
// enumerable: true
// value: 29
// writable: true
// job:
// configurable: true
// enumerable: true
// value: "SoftWare Engineer"
// writable: true
// name:
// configurable: true
// enumerable: true
// value: "ChangLau"
// writable: true
// sayName:
// configurable: true
// enumerable: true
// value: ƒ ()
// writable: true
修改默认数据属性值
// 不可重写
var person = {}
Object.defineProperty(person, 'name', {
writable: false,
value: "ChangLau"
})
console.log(person.name) // ChangLau
person.name = 'Donbad'
console.log(person.name); // ChangLau
// 不可配置(定义不可配置之后,不能变回配置)
var person = {}
Object.defineProperty(person, 'name', {
configurable: false,
value: "ChangLau"
})
console.log(person.name); // ChangLau
delete person.name
console.log(person.name); // ChangLau
通过 Object.defineProperty 创建新的属性,数据属性值默认为 false
var person = {}
Object.defineProperty(person, 'name', {
configurable: false,
value: "ChangLau"
})
Object.getOwnPropertyDescriptors(person)
// name:
// configurable: false
// enumerable: false
// value: "ChangLau"
// writable: false
访问器属性
包含一对 getter 和 setter 函数,用于返回和设置值
- [[Configurable]] 表示是否能够通过 delete 删除属性从而重新定义属性,能否修改属性的特性,或者能否把属性修改为数据属性
- [[Enumerable]] 表示能否通过 for-in 循环返回属性
- [[Get]] 读取属性时调用的函数
- [[Set]] 写入属性时调用的函数
var book = {
_year: 2004,
edition: 1
}
Object.defineProperty(book, 'year', {
get: function(){
return this._year
},
set: function(newValue){
if(newValue > 2004){
this._year = newValue
this.edition += newValue - 2004
}
}
})
book.year = 2005 // {_year: 2005, edition: 2}
定义多个属性
var book = {}
Object.defineProperties(book, {
_year: {
writable: true,
value: 2004
},
edition: {
writable: true,
value:1
},
year:{
get: function(){
return this._year
},
set: function(newValue){
if(newValue > 2004){
this._year = newValue
this.edition += newValue - 2004
}
}
}
})
读取属性的特性
Object.getOwnPropertyDescriptor(book, '_year') // {value: 2005, writable: true, enumerable: false, configurable: false}
Object.getOwnPropertyDescriptor(book, 'year') // {get: ƒ, set: ƒ, enumerable: false, configurable: false}
Object.getOwnPropertyDescriptors(book)
// edition: {value: 2, writable: true, enumerable: false, configurable: false}
// year: {get: ƒ, set: ƒ, enumerable: false, configurable: false}
// _year: {value: 2005, writable: true, enumerable: false, configurable: false}