JavaScript手写实现call,apply,bind方法

手写call()方法

系统用法:

function.call(thisArg, arg1, arg2, ...)

手写实现:

function sum(num1, num2) {
    
    
  console.log(num1 + num2, this)
  return num1 + num2;
}

Function.prototype.mjycall = function(thisArg, ...payload) {
    
    
  // 这里的this是指向的是:调用mjycall方法时,默认绑定的sum方法
  // 将隐式绑定的方法命名为fn,之后我们将改变这个fn方法中this的指向,并进行调用
  var fn = this

  // thisArg 是我们要更改绑定后的this指向,要进行对象化处理,并且处理一些null、undefinded边界问题。
  thisArg = thisArg === null || undefined ? window : Object(thisArg)

  // 将fn方法绑定到要指向的对象上,并进行调用
  thisArg.fn = fn
  let res = thisArg.fn(...payload)
  delete thisArg.fn
  return res
}

sum.mjycall("123", 10, 20)
var sum = sum.mjycall(null, 10, 20)
console.log('sum==>', sum)

手写apply()方法

系统方法:

function.call(thisArg, [arg1. arg2, ...])

手写实现:

// 手写实现apply方法和call非常类似,看懂call后apply实现也很简单
function sum(num1, num2) {
    
    
  console.log(num1 + num2, this)
  return num1 + num2;
}

// 就不需要参数扩展运算符了,apply参数本身是一个整体数组
Function.prototype.mjyapply = function(thisArg, payload) {
    
    
  var fn = this

  thisArg = thisArg === null || undefined ? window : Object(thisArg)

  thisArg.fn = fn
  let res = thisArg.fn(...payload)
  delete thisArg.fn
  return res
}

sum.mjyapply("123", [10, 20])
var sum = sum.mjyapply(null, [10, 20])
console.log('sum==>', sum)

手写bind()方法

系统方法:

newfunction = function.bind(thisArg[, arg1[, arg2[, ...]]])

bind(),方法就比较特殊,bind()将生成一个新函数,将新函数的this指向进行更改。而且bind的传参方式很多样。

手写实现bind():

function sum(num1, num2, num3, num4) {
    
    
  console.log(num1 + num2 + num3 + num4, this)
  return num1 + num2 + num3 + num4;
}

Function.prototype.mjybind = function(thisArg, ...payload1) {
    
    
  // 这里的this是指向的是:调用mjycall方法时,默认绑定的sum方法
  // 将隐式绑定的方法命名为fn,之后我们将改变这个fn方法中this的指向,并进行调用
  var fn = this

  // thisArg 是我们要更改绑定后的zhis指向,要进行对象化处理,并且处理一些null、undefinded边界问题。
  thisArg = thisArg === null || undefined ? window : Object(thisArg)

  // bind()方法返回的是一个新的函数,并有可能会在新的函数中继续传值
  return function(...payload2) {
    
      
    thisArg.fn = fn
    // 最终调用fn时,我们把参数都传递进去
    var res = thisArg.fn(...payload1, ...payload2)
    delete thisArg.fn
    return res 
  }
}

foo = sum.mjybind("123", 10, 20)
foo(30, 40)

foo2 = sum.mjybind("123", 10, 20, 30, 40)
console.log(foo2())

声明

  • 本文属于读书笔记一类,是作者在学习 《深入JavaScript高级语法》 coderwhy老师课程途中,以视频中内容为蓝本,辅以个人微末的道行“填写”完成,推荐购买原课程观看,定有收获
  • 欢迎大佬斧正

猜你喜欢

转载自blog.csdn.net/qq_45934504/article/details/124913567
今日推荐