[Javascript] Proxy vs defineProperty in low level
Proxy
The
Proxy
object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
So what does it mean for fundamental operations for object
?
In javascript, we can do following opeartion against Object
const obj = {}
obj.a
obj.b = 2
Object.setPrototypeOf(obj, { c: 3})
Object.getPrototypeOf(obj)
for (const key in obj) {
}
But EMCAScript will transform those human readable code into it's internal function:
const obj = {}
obj.a // [[GET]]
obj.b = 2 // [[SET]]
Object.setPrototypeOf(obj, { c: 3}) // [[SetPrototypeOf]]
Object.getPrototypeOf(obj) // [[GetPrototypeOf]]
for (const key in obj) { // [[OwnPropertyKeys]]
}
Source: https://ecma-international.org/publications-and-standards/standards/ecma-262/
Difference between Proxy vs defineProperty
After knowning what is the fundamental operations for object, let's what's the difference between proxy and defineProperty.
Notice [[DefineOwnProperty]]
in the table.
It's actually the fundamental operations for Object.defineProperty
Therefore, Proxy
can intercept and redefine fundamental opeartions (which includes [[DefineOwnProperty]])
And Object.defineProperty
is just one of the fundamental operation in Javascript, it cannot redefine or intercept anything.
Real usecase
In Vue2, it uses a lot Object.defineProperty
to achieve object reactivity. But for array operation, Vue2 cannot use defineProperty.
const arr = [1,2,3]
arr.push(1)
So Vue2 actually create a middle layer of VArray prototype which wraps all the methods push, pop...
And VArray prototype will point to the Javascript Array prototype.
In Vue3, due to the power of proxy, which can redefine and intercept any object
const arr = [1,2,3]
const p = new Proxy(arr, {
get(target, prop) {
console.log('get', prop)
return target[prop]
},
set(target, prop, value) {
console.log('set', prop, value)
target[prop] = value
return true
}
})
p.push(1)
/*
get push
get length
set 3 1
set length 4
*/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-10-10 [Typescript] Type and Interface for performance
2022-10-10 [Typescript] Tips: Create autocomplete helper which allows for arbitrary values
2022-10-10 [Typescript] Tips: DeepPartial
2019-10-10 [Svelte 3] Use Svelte 3 transitions to gracefully show and hide DOM elements
2019-10-10 [TypeScript ] Using the Null Coalescing operator with TypeScript 3.7
2019-10-10 [TypeScript] Optional Chaining with TypeScript 3.7
2019-10-10 [Flutter] Custom a Slider with SliderTheme