当前位置:网站首页>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 ]
边栏推荐
- Anaconda uses China University of science and technology source
- DVWA range clearance tutorial
- MySQL----函数
- Jmeter性能测试:ServerAgent资源监控
- I want to inquire about how to ensure data consistency when a MySQL transaction updates multiple tables?
- 12 MySQL interview questions that you must chew through to enter Alibaba
- Calculate weight and comprehensive score by R entropy weight method
- Under the crisis of enterprise development, is digital transformation the future savior of enterprises
- MongDB学习笔记
- Reasons and solutions for redis cache penetration and cache avalanche
猜你喜欢

计算中间件 Apache Linkis参数解读

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

1330:【例8.3】最少步数

Crud of MySQL
![P6183 [USACO10MAR] The Rock Game S](/img/f4/d8c8763c27385d759d117b515fbf0f.png)
P6183 [USACO10MAR] The Rock Game S

How can I quickly check whether there is an error after FreeSurfer runs Recon all—— Core command tail redirection

Bugku's Eval

当代人的水焦虑:好水究竟在哪里?

Bugku cyberpunk

Interpretation of Apache linkage parameters in computing middleware
随机推荐
I spring and autumn blasting-1
How can I quickly check whether there is an error after FreeSurfer runs Recon all—— Core command tail redirection
社区团购撤城“后遗症”
Huawei Hubble incarnation hard technology IPO harvester
Coding devsecops helps financial enterprises run out of digital acceleration
Hongmeng system -- Analysis from the perspective of business
The difference between SQL Server char nchar varchar and nvarchar
Surpass palm! Peking University Master proposed diverse to comprehensively refresh the NLP reasoning ranking
Creation and use of thymeleaf template
Redis distributed lock principle and its implementation with PHP (1)
ICML 2022 | explore the best architecture and training method of language model
Au - delà du PARM! La maîtrise de l'Université de Pékin propose diverse pour actualiser complètement le classement du raisonnement du NLP
sql server char nchar varchar和nvarchar的区别
ICML 2022 | 探索语言模型的最佳架构和训练方法
复现Thinkphp 2.x 任意代码执行漏洞
MongDB学习笔记
P1451 calculate the number of cells / 1329: [example 8.2] cells
Stm32+bh1750 photosensitive sensor obtains light intensity
Common MySQL interview questions (1) (written MySQL interview questions)
R 熵权法计算权重及综合得分