[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, Proxycan intercept and redefine fundamental opeartions (which includes [[DefineOwnProperty]])

And Object.definePropertyis just one of the fundamental operation in Javascript, it cannot redefine or intercept anything.

 

Real usecase

In Vue2, it uses a lot Object.definePropertyto 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
*/

 

posted @ 2024-10-10 15:16  Zhentiw  阅读(20)  评论(0)    收藏  举报