Reflect.get()

Baseline 已廣泛支援

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

Reflect.get() 靜態方法類似於屬性訪問器語法,但它是一個函式。

試一試

const object = {
  x: 1,
  y: 2,
};

console.log(Reflect.get(object, "x"));
// Expected output: 1

const array = ["zero", "one"];

console.log(Reflect.get(array, 1));
// Expected output: "one"

語法

js
Reflect.get(target, propertyKey)
Reflect.get(target, propertyKey, receiver)

引數

目標

要獲取屬性的目標物件。

propertyKey

要獲取的屬性名稱。

receiver 可選

如果遇到 getter,則在呼叫 target 時提供給 this 的值。

返回值

屬性的值。

異常

TypeError

如果 target 不是一個物件,則丟擲。

描述

Reflect.get() 提供了屬性訪問的反射語義。也就是說,Reflect.get(target, propertyKey, receiver) 在語義上等同於

js
target[propertyKey];

請注意,在正常的屬性訪問中,targetreceiver 在可觀察上是相同的物件。

Reflect.get() 呼叫 target[[Get]] 物件內部方法

示例

使用 Reflect.get()

js
// Object
const obj1 = { x: 1, y: 2 };
Reflect.get(obj1, "x"); // 1

// Array
Reflect.get(["zero", "one"], 1); // "one"

// Proxy with a get handler
const obj2 = new Proxy(
  { p: 1 },
  {
    get(t, k, r) {
      return `${k}bar`;
    },
  },
);
Reflect.get(obj2, "foo"); // "foobar"

// Proxy with get handler and receiver
const obj3 = new Proxy(
  { p: 1, foo: 2 },
  {
    get(t, prop, receiver) {
      return `${receiver[prop]}bar`;
    },
  },
);
Reflect.get(obj3, "foo", { foo: 3 }); // "3bar"

規範

規範
ECMAScript® 2026 語言規範
# sec-reflect.get

瀏覽器相容性

另見