Reflect.apply()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Phương thức tĩnh Reflect.apply() gọi một hàm target với các đối số được chỉ định.
Try it
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"
Cú pháp
Reflect.apply(target, thisArgument, argumentsList)
Tham số
target-
Hàm target cần gọi.
thisArgument-
Giá trị của
thisđược cung cấp cho lời gọi đếntarget. argumentsList-
Một đối tượng giống mảng xác định các đối số mà
targetsẽ được gọi cùng.
Giá trị trả về
Kết quả của việc gọi hàm target đã cho với giá trị this và các đối số được chỉ định.
Ngoại lệ
TypeError-
Được ném ra nếu
targetkhông phải là hàm hoặcargumentsListkhông phải là đối tượng.
Mô tả
Reflect.apply() cung cấp ngữ nghĩa phản chiếu của một lời gọi hàm. Tức là, Reflect.apply(target, thisArgument, argumentsList) tương đương về mặt ngữ nghĩa với:
Math.floor.apply(null, [1.75]);
Reflect.apply(Math.floor, null, [1.75]);
Sự khác biệt duy nhất là:
Reflect.apply()nhận hàm cần gọi làm tham sốtargetthay vì ngữ cảnhthis.Reflect.apply()ném ra lỗi nếuargumentsListbị bỏ qua thay vì mặc định gọi mà không có tham số nào.
Reflect.apply() gọi phương thức nội tại [[Call]] của đối tượng trên target.
Ví dụ
>Sử dụng Reflect.apply()
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"
Đặc tả kỹ thuật
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-reflect.apply> |