Reflect.apply()
åºçº¿
广æ³å¯ç¨
èª 2016å¹´9æ èµ·ï¼æ¤ç¹æ§å·²å¨ä¸»æµæµè§å¨ä¸å¾å°æ¯æï¼å¯å¨å¤§å¤æ°è®¾å¤åæµè§å¨çæ¬ä¸æ£å¸¸ä½¿ç¨ã
éææ¹æ³ Reflect.apply() éè¿æå®çåæ°å表åèµ·å¯¹ç®æ (target) 彿°çè°ç¨ã
å°è¯ä¸ä¸
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"
è¯æ³
Reflect.apply(target, thisArgument, argumentsList)
åæ°
- target
-
ç®æ 彿°ã
- thisArgument
-
target 彿°è°ç¨æ¶ç»å®ç this 对象ã
- argumentsList
-
target 彿°è°ç¨æ¶ä¼ å ¥çå®åå表ï¼è¯¥åæ°åºè¯¥æ¯ä¸ä¸ªç±»æ°ç»ç对象ã
è¿åå¼
è¿å弿¯è°ç¨å®å¸¦çæå®åæ°å this å¼çç»å®ç彿°åè¿åçç»æã
å¼å¸¸
妿 target 对象ä¸å¯è°ç¨ï¼æåº TypeErrorã
æè¿°
è¯¥æ¹æ³ä¸ ES5 ä¸Function.prototype.apply()æ¹æ³ç±»ä¼¼ï¼è°ç¨ä¸ä¸ªæ¹æ³å¹¶ä¸æ¾å¼å°æå® this åéååæ°å表 (arguments) ï¼åæ°å表å¯ä»¥æ¯æ°ç»ï¼æç±»ä¼¼æ°ç»ç对象ã
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
ä½¿ç¨ Reflect.apply æ¹æ³ä¼ä½¿ä»£ç æ´å ç®æ´ææã
使ç¨ç¤ºä¾
>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"
è§è
| è§è |
|---|
| ECMAScript® 2027 Language Specification> # sec-reflect.apply> |