Reflect
为操作对象提供的新API
列举常用的API
代码语言:javascript复制const obj = {
name: 'swt',
age: 20
}
/*
* 属性写入
*/
Reflect.set(obj, 'sex', '男')
console.log(obj) // {name: "swt", age: 20, sex: "男"}
/*
* 属性读取
*/
const a = Reflect.get(obj, 'name')
console.log(a) // swt
/*
* 属性删除
*/
Reflect.deleteProperty(obj, 'sex')
console.log(obj) // {name: "swt", age: 20}
/*
* 属性包含
*/
const b = Reflect.has(obj, 'name')
console.log(b) // true
/*
* 属性遍历
*/
const c = Reflect.ownKeys(obj)
console.log(c) // ["name", "age", "sex"]
Proxy
对象属性读写
代码语言:javascript复制const person = {
name: 'cyw',
age: 20
}
const personProxy = new Proxy(person, {
get(obj, key) {
return key in obj ? obj[key] : 'default'
},
set(obj, key, value) {
if(key === 'age') {
if(!Number.isIntegr(value)) {
throw new TypeError(`${value} is not an int`)
}
}
obj[key] = value
}
})
personProxy.age = 10.5 // Uncaught TypeError: 10.5 is not an int
console.log(personProxy.name) // cyw
console.log(personProxy.sex) // default
监视数组操作
代码语言:javascript复制const list = []
const listProxy = new Proxy(list, {
set(obj, key, value) {
console.log('set', key, value)
obj[key] = value
return true
}
})
listProxy.push(100)
// set 0 100
// set length 1