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 |
瀏覽器相容性
載入中…