試一試
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];
請注意,在正常的屬性訪問中,target 和 receiver 在可觀察上是相同的物件。
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 |
瀏覽器相容性
載入中…