实现call

  1. call 会立即调用函数
  2. 第一个参数是指定对象,后面的都是传入的参数
  3. 如果第一个参数传入 undefined、null 会指向window
  1. Function.prototype.myCall = function (thisArg, ...args) {
  2. const fn = this
  3. thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : window
  4. thisArg.fn = fn
  5. const result = thisArg.fn(...args)
  6. delete thisArg.fn
  7. return result
  8. }
  9. function sum(num1, num2) {
  10. console.log(this)
  11. return num1 + num2
  12. }
  13. const res = sum.myCall('123', 20, 30)
  14. console.log(res)

实现apply

  1. apply 会立即调用函数
  2. 第一个参数是指定对象,传参是以数组的方式
  3. 如果第一个参数传入 undefined、null 会指向window
  1. Function.prototype.myApply = function (thisArg, arrArg) {
  2. const fn = this
  3. thisArg = (thisArg !== undefined && thisArg != null) ? Object(thisArg) : window
  4. thisArg.fn = fn
  5. arrArg = arrArg || []
  6. const res = thisArg.fn(...arrArg)
  7. delete thisArg.fn
  8. return res
  9. }
  10. function sum(num1, num2) {
  11. return num1 + num2
  12. }
  13. const res = sum.myApply("123", [20, 30])
  14. console.log(res);

实现bind

  1. 不会立即调用函数,会返回一个变更后的函数
  2. 第一个参数是指定对象,后面的都是传入的参数
  3. 如果第一个参数传入 undefined、null 会指向window
  4. 可以分开传参,const foo = bind(this,1,2);foo(3,4)
  1. Function.prototype.myBind = function (thisArg, ...arrArgs) {
  2. const fn = this
  3. thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
  4. function proxyFn(...args) {
  5. thisArg.fn = fn
  6. const res = thisArg.fn(...arrArgs, ...args)
  7. delete thisArg.fn
  8. return res
  9. }
  10. return proxyFn
  11. }
  12. function foo(num1, num2) {
  13. console.log(this);
  14. console.log(num1, num2);
  15. return num1 + num2
  16. }
  17. // foo.myBind("123", 10, 20)
  18. const bar = foo.myBind("123", 10, 20)
  19. console.log(bar());