本文是js红宝书第八章总结
属性的两种类型
内部特性用来描述属性的特征,无法直接访问(要通过访问器),以[[]]进行标识
特性就是为了某个概念而定义的专一的东西,不能把属性看作是数据属性+访问器属性组成的对象
- 数据属性
- [[Configurable]]是否可以delete,是否可以改为访问器属性,一般为true
- [[Enumberable]]是否可以通过for-in循环返回,一般都是true
- [[Writable]]值是否能被修改
- [[Value]]
简单点说,这些特性用来描述
举个例子:person.name = "lpj"
name的数据属性的[[value]]就是"lpj" ,但你不能直接用[]获取,这些内部特性是工具人,用来描述数据的
可以用Object.defineProperty方法进行修改默认值
注意:把属性定义为不可配置后,就不能变回可配置的了
- 访问器属性
不包含数据,包含一个获取(getter)函数和设置(setter)函数 以下属性描述他们的行为- [[Configurable]]
- [[Enumerable]]
- [[Get]]方法 读取属性值
- [[Set]]方法 修改属性值
典型访问器属性应用场景,即设置一个属性值会导致一些变化发生
let book = {
year_:2021,//伪私有成员(指该属性需用set函数进行操作)
edition:1
}
Object.defineProperty(book,"year",{
/*这里会新增year属性,
但由于使用了definePropert,
这个属性会被覆写为如下的内部特性(由于没设置[[Value]] 它也就没有数据值啦,单纯是工具人访问year_)*/
get(){
//简单返回属性值
return this.year_;
},
set(newValue){
//对写入的值进行处理 注意如果写为空的话 就是只读属性了
if (newValue>2021) {
this.year_ = newValue
this.edition++
}
else
this.year_ = newValue
}
})
console.log(book.year)//值为2021,edition=1
book.year = 2077;//尝试修改year,会被Editon记录,当然这里你直接修改year_的话就没辙了
console.log(book.year)//edition=2
为什么console看对象时看不到原来的属性值,而总是显示最新的值?
Simply what it says is that the console evaluated the object just as you press the expand icon. Here is a test.
1:Type o = {} in the console. The output will be something like >{}. DON'T EXPAND YET!
2:Add a property to the o object. o.x = 1
3:Now go back and expand the previous output. It will have the x property you added obviously after that output was created. But the the output still have the x val
——Stack Overflow
可以通过Object.define-Properties()实现一次性同时定义多个多个属性
- ES6对象拓展方法
- 通过getOwnPropertyDescriptor()读取属性的特性
- 合并对象:
Object.assign(dest, src)
把src复制进dest - 对象相等精确判定Object.is() 与===很像
- 可计算属性,es6可以在字面量直接进行动态命名属性
let nameKey = name
let person = {
[nameKey] = 'lpj'
}
console.log(person.name=='lpj')//true
//以前必须先声明对象
//再person[nameKey] = 'hjy'这样
这意味着可以使用复杂表达式甚至是函数,但要小心表达式副作用,如果抛出错误会导致对象创建中断,且不可回滚
- 对象解构
let person = {
name:'pj',
age:19
}
//不使用解构
let personName = person.name
let personAge = person.age
//使用解构语法
let { name:personName , age: personAge} = person;
//注意冒号前后
解构在红宝书中篇幅蛮大的,其语法和用法比较多变