1. 程式人生 > 其它 >手寫 call apply bind

手寫 call apply bind

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>call&apply&bind</title>
  </
head> <body> <script> // 將方法掛載到物件上 // 執行物件的方法 // 將這個方法從物件上移除 Function.prototype.myCall = function (context, ...args) { let fn = Symbol(1); context[fn] = this; context[fn](...args); Reflect.deleteProperty(context, 'fn'); }; Function.prototype.myApply
= function (context, args = []) { let fn = Symbol(1); if (args && !(args instanceof Array)) { throw 'error'; } context[fn] = this; context[fn](...args); Reflect.deleteProperty(context, 'fn'); }; Function.prototype.myBind =
function (context, ...args) { return (...args2) => { let fn = Symbol(1); context[fn] = this; context[fn](...args.concat(...args2)); Reflect.deleteProperty(context, 'fn'); }; }; </script> </body> </html>