当前位置:网站首页>Object. defineProperty() - VS - new Proxy()
Object. defineProperty() - VS - new Proxy()
2022-07-05 15:21:00 【Shepherd Wolf】
Catalog
Object.defineProperty The defects of
1. Cannot detect new or delete object properties
2. Unable to listen for array changes
Vue2.0 :
adopt Object.defineProperty Method property interception method , hold data The reading and writing of each data in the object is transformed into getter/setter, Notify view to update when data changes .
Object.defineProperty()
grammar :
Object.defineProperty(obj, property, descriptor)
Next, we will focus on the third parameter :descriptor:
stay JS Objects in have two properties , They are data attributes and accessor attributes ,
So its descriptors are also classified according to attributes , It is divided into Data descriptor and Accessor descriptor .
When using descriptors , It must be one of two forms , And You can't use both at the same time .
When using the getter or setter Method , Not allowed writable and value These two properties ( If you use , Will directly report an error )
Data descriptor
Have the following optional key values :
configurable: Indicates whether the attribute can pass delete Delete , Whether to modify the properties of attributes or whether to modify accessor attributes , The default is false.
enumerable: Indicates whether the attribute can be enumerated , That is, whether it can be passed for..in Access properties . The default is false.value: Represents the value of the property . It can be anything that works JS value . The default is undefined.
writable: Indicates whether the value of the property is writable , The default is false.
Accessor descriptor
Have the following optional key values :
configurable: Indicates whether the attribute can pass delete Delete , Whether to modify the properties of attributes or whether to modify accessor attributes , The default is false.
enumerable: Indicates whether the attribute can be enumerated , That is, whether it can be passed for..in Access properties . The default is false.get: Function called when reading properties , The default value is undefined.
set: The function called when the property is written , The default value is undefined.
const user = {
age: 18,
wife: {
name: 'xiao',
age: 17
}
}
var newName = 'wang'
Object.defineProperty(user, 'name', {
get () {
console.log('get Method is called ')
return newName
},
set (val) {
console.log('set Method is called ')
newName = val
}
})
console.log(user.name)
user.name = 'lao wang'
console.log(user.name)The results are as follows :

new Proxy()
new Proxy() Turn the target object into a proxy object
Parameters 1: user -----> target Target audience
Parameters 2: handler --> Processor object , Used to monitor data , And data operation
const user = {
name: 'wang',
age: 18,
wife: {
name: 'xiao',
age: 17
}
}
const proxyUser = new Proxy(user, {
get (target, property) { // Read a property value of the target object
console.log('get Method is called ')
return Reflect.get(target, property)
},
set (target, property, val) { // modify / Add property value
console.log('set Method is called ')
return Reflect.set(target, property, val)
},
deleteProperty(target, property) { // Delete a property of the target object
console.log('delete Method is called ')
return Reflect.deleteProperty(target, property)
}
})
// By proxy object :
// check --- Get a property value in the target object
console.log(proxyUser.name)
// Change --- Update a property value in the target object
proxyUser.name = 'lao wang'
console.log(user)
// increase --- Add a new attribute value to the target object
proxyUser.sex = 'male'
console.log(user)
// Delete --- Delete a property value of the target object
delete proxyUser.name
console.log(user)The results are as follows :

Object.defineProperty The defects of
const data = {
name: '',
};
// Traversing objects , Hijack its property value
Object.keys(data).forEach(function(key) {
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function() {
},
set: function(newVal) {
// We can do something extra when the property value changes
console.log(` Hello everyone , My department ${newVal}`);
},
});
});
data.name = ' Residue residue ';although Object.defineProperty By setting... For properties getter/setter Be able to complete the data response , But it's not the perfect way to make data responsive , The main defects are :
1. Cannot detect new or delete object properties ( Add attributes directly 、 Delete attribute , The page will not be updated );
2. Unable to listen for array changes ( Modify the array directly by subscript , The interface doesn't update automatically .)
Cannot detect new or delete object properties
<p>{
{obj}}</p>
<p>{
{arr}}</p>
data(){
return {
obj:{
a:2
}
}
},
mounted () {
this.obj.b = 222
},
<!-- obj Show results -->
//obj:{ "a": 2 }resolvent :
(1) Attribute added :
this.obj = Object.assign({},this.obj, { b: 1, e: 2 })
this.obj = {...this.obj,...{ b: 3, e: 2 }}
this.$set(this.obj,'f',0) // or vue.set(this.obj,'f',0)
(2) Delete attribute :
this.$delete(obj, propertyName/index) // or vue.delete(obj, propertyName/index)
Unable to listen for array changes
<p>{
{arr}}</p>
data(){
return {
arr:[1,2]
}
},
mounted () {
this.arr[0]= 3333
},
<!-- arr Show results -->
arr:[ 1, 2 ]
边栏推荐
- 我这边同时采集多个oracle表,采集一会以后,会报oracle的oga内存超出,大家有没有遇到的?
- 爱可可AI前沿推介(7.5)
- 数据库学习——数据库安全性
- The elimination strategy of redis
- Handwriting promise and async await
- 当代人的水焦虑:好水究竟在哪里?
- Want to ask the big guy, is there any synchronization from Tencent cloud Mysql to other places? Binlog saved by Tencent cloud MySQL on cos
- Your childhood happiness was contracted by it
- Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification
- [JVM] operation instruction
猜你喜欢

Ctfshow web entry information collection

B站做短视频,学抖音死,学YouTube生?

ionic cordova项目修改插件

I spring and autumn blasting-2

Bugku easy_ nbt

市值蒸发超百亿美元,“全球IoT云平台第一股”赴港求生

Usage and usage instructions of JDBC connection pool

qt creater断点调试程序详解

社区团购撤城“后遗症”

Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel
随机推荐
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
Redis distributed lock principle and its implementation with PHP (1)
Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发
Hongmeng system -- Analysis from the perspective of business
漫画:优秀的程序员具备哪些属性?
How can the boss choose programmers to help me with development?
Reasons and solutions for redis cache penetration and cache avalanche
lv_font_conv离线转换
Install and configure Jenkins
JMeter performance test: serveragent resource monitoring
go学习 ------jwt的相关知识
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
P1451 calculate the number of cells / 1329: [example 8.2] cells
CPU design related notes
Using tensorboard to visualize the training process in pytoch
Creation and optimization of MySQL index
可转债打新在哪里操作开户是更安全可靠的呢
Photoshop plug-in action related concepts actionlist actiondescriptor actionlist action execution load call delete PS plug-in development
CODING DevSecOps 助力金融企业跑出数字加速度
Dark horse programmer - software testing -10 stage 2-linux and database -44-57 why learn database, description of database classification relational database, description of Navicat operation data, de