[Javascript] Reflect vs obj[key]

Zhentiw發表於2024-11-17

The Reflect namespace object contains static methods for invoking interceptable JavaScript object internal methods. The methods are the same as those of proxy handlers.

For internal methods such as [[GET]]

https://262.ecma-international.org/15.0/index.html?_gl=1*1wddf7i*_ga*MjAxMzMxOTcxMy4xNzMxNzgzMzU4*_ga_TDCK4DWEPP*MTczMTc4MzM1Ny4xLjAuMTczMTc4MzM1Ny4wLjAuMA..

Return the value of the property whose key is propertyKey from this object. If any ECMAScript code must be executed to retrieve the property value, Receiver is used as the this value when evaluating the code.

So for a proy handler, should we use target[key], or Reflect.get?

// using target[key]
function get(target, key, receiver) {
    return target[key]
}

// using Reflect.get
function get(target, key, receiver) {
    return Reflect.get(target, key, receiver)
}

new Proxy(target, {get})

Example:

const obj = {
    a: 1,
    b: 2,
    get c() {
        console.log(this)
        return this.a + this.b
    }
}

// use traget[key]
// internal method target[[GET]](key, target)
// this points to obj itself

// use Reflect.get(target, key, receiver)
// internal method you can tell the receiver
// this points to the Proxy

相關文章