Reflect.get()

Reflect.get() 静态方法类似于 属性访问器 语法,但作为一个函数。

¥The Reflect.get() static method is like the property accessor syntax, but as a function.

Try it

语法

¥Syntax

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

参数

¥Parameters

target

要获取其属性的目标对象。

propertyKey

要获取的属性的名称。

receiver Optional

如果遇到 getter,则为调用 target 提供 this 的值。

返回值

¥Return value

属性的价值。

¥The value of the property.

例外情况

¥Exceptions

TypeError

如果 target 不是对象,则抛出该异常。

描述

¥Description

Reflect.get() 提供 属性访问权 的反射语义。也就是说,Reflect.get(target, propertyKey, receiver) 在语义上等同于:

¥Reflect.get() provides the reflective semantic of a property access. That is, Reflect.get(target, propertyKey, receiver) is semantically equivalent to:

js
target[propertyKey];

请注意,在正常的属性访问中,targetreceiver 显然是同一个对象。

¥Note that in a normal property access, target and receiver would observably be the same object.

Reflect.get() 调用 target[[Get]] 对象内部方法

¥Reflect.get() invokes the [[Get]] object internal method of target.

示例

¥Examples

使用 Reflect.get()

¥Using 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"

规范

Specification
ECMAScript Language Specification
# sec-reflect.get

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看