Reflect.apply()
Reflect.apply() 静态方法会根据指定的方式调用目标函数。
试一试
console.log(Reflect.apply(Math.floor, undefined, [1.75]));
// Expected output: 1
console.log(
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]),
);
// Expected output: "hello"
console.log(
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index,
);
// Expected output: 4
console.log(Reflect.apply("".charAt, "ponies", [3]));
// Expected output: "i"
语法
js
Reflect.apply(target, thisArgument, argumentsList)
参数
目标-
要调用的目标函数。
thisArgument-
调用
target时提供的this值。 argumentsList-
一个 类数组对象,指定了调用
target时使用的参数。
返回值
使用指定的 this 值和参数调用给定的 target 函数的结果。
异常
TypeError-
如果
target不是函数或argumentsList不是对象,则抛出此错误。
描述
Reflect.apply() 提供了函数调用的反射语义。也就是说,Reflect.apply(target, thisArgument, argumentsList) 在语义上等同于
js
Math.floor.apply(null, [1.75]);
Reflect.apply(Math.floor, null, [1.75]);
唯一的区别是
Reflect.apply()将要调用的函数作为target参数,而不是this上下文。- 如果省略
argumentsList,Reflect.apply()会抛出错误,而不是默认使用无参数调用。
Reflect.apply() 调用 target 的 [[Call]] 对象内部方法。
示例
使用 Reflect.apply()
js
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4
Reflect.apply("".charAt, "ponies", [3]);
// "i"
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-reflect.apply |
浏览器兼容性
加载中…