JavaScript - Reflect 对象
JavaScript Reflect
在 JavaScript 中,Reflect 是一个全局对象,是在 ECMAScript 6 (ES6) 中引入的。它包含静态方法,提供了一种在运行时与对象交互的更好方式。
与大多数全局对象不同,Reflect 不是构造函数。您不能将其与 new 运算符一起使用,也不能将 Reflect 对象作为函数调用。 Reflect 的所有方法都是静态的,就像 Math 对象一样。
它包含各种方法,用于在运行时访问、更新、删除等对象的属性。
Reflect 对象的主要特性
对象构造 − Reflect API 允许使用 Reflect.construct() 方法在运行时创建对象。
函数调用 − Reflect API 的 apply() 方法用于通过传递上下文和参数来调用函数或对象方法。
对象属性操作 − Reflect API 提供多种方法来设置、更新或删除对象属性。此外,它还可以通过阻止对象扩展来处理扩展。
语法
以下是使用 Reflect API 方法的语法 -
Reflect.method();
在上述语法中,"方法"是泛化。它可以是 Reflect API 的任何方法,例如 get、set、apply、construct、has 等。
Reflect 方法
下表列出了 Reflect 的所有方法 -
| Sr.No. | 名称 &说明 |
|---|---|
| 1 |
调用函数。 |
| 2 |
允许指定不同的原型。 |
| 3 |
允许插入或编辑对象属性。 |
| 4 |
允许删除对象属性。 |
| 5 |
获取属性值。 |
| 6 |
允许获取对象的描述符。 |
| 7 |
获取对象的原型。 |
| 8 |
检查对象中是否存在该属性。 |
| 9 |
允许检查对象是否可扩展。 |
| 10 |
返回目标对象自身的键,并忽略继承的键键。 |
| 11 |
阻止对象的扩展。 |
| 12 |
将值设置为对象属性。 |
| 13 |
允许设置对象的原型为 null 或其他对象。 |
示例
示例 1
在下面的示例中,我们定义了一个 car 对象。"prop"变量包含字符串格式的属性名称。
我们使用 Reflect 对象的 get() 方法从 car 对象访问"model"属性。我们将对象名称作为 get() 方法的第一个参数传递,并将属性名称作为第二个参数传递。
在输出中,您可以看到"model"属性的值。
<html>
<body>
<div id="output">The model of the car is: </div>
<script>
const car = {
name: "Audi",
model: "Q6",
price: 7000000,
}
let prop = "model";
let model = Reflect.get(car, prop);
document.getElementById("output").innerHTML += model;
</script>
</body>
</html>
输出
The model of the car is: Q6
示例 2
在下面的示例中,我们使用 set() 方法将属性设置到对象中。set() 方法接受对象、属性名称和值作为参数。
输出显示了"doors"属性值。这样,您就可以在运行时使用 Reflect API 的 set() 方法将属性设置到对象中。
<html>
<body>
<div id="output">The total doors in the Audi Q6 is: </div>
<script>
const car = {
name: "Audi",
model: "Q6",
price: 7000000,
}
const model = Reflect.set(car, "doors", 4);
document.getElementById("output").innerHTML += car.doors;
</script>
</body>
</html>
输出
The total doors in the Audi Q6 is: 4
执行上述脚本后,将弹出输出窗口,并在网页上显示文本。
示例 3
在下面的示例中,我们使用 has() 方法动态检查对象中是否存在特定属性。
这两个符号看起来相似,但实际上有所不同,您可以在输出中看到这一点。
<html>
<body>
<p id="output"></p>
<script>
const car = {
name: "Audi",
model: "Q6",
price: 7000000,
}
const isName = Reflect.has(car, "name");
if (isName) {
document.getElementById("output").innerHTML = "The Car object contains the name.";
}
</script>
</body>
</html>
输出
The Car object contains the name.

