首页 > 其他分享 >bind实现

bind实现

时间:2022-10-30 00:34:31浏览次数:28  
标签:function 函数 实现 bind age 调用者 let name

Function.prototype.myBind = function (context) { //
  if(!(typeof this == 'function')) {      //1.判断调用者是否为一个函数          判
    throw new Error('调用者必须是一个函数')
  }
  let self = this; //2.保存调用函数   保

  let args = [...arguments].slice(1);//3.获取调用者传递参数    // 调参

  let fn = function() {}//4.创建临时函数  临

  const bound = function() { //5.创建返回的绑定函数  创
    let arg = [...arguments];//6.获取绑定后参数  绑参
    let res = self.apply(this instanceof self ? this : context, args.concat(arg))//7.判断是否为new调用,并执行函数  执
    return res//8.返回执行结果 返
  }
  fn.prototype = self.prototype; //9.临时函数原型指向调用者原型  指
  bound.prototype = new fn();//10.绑定函数继承临时函数   继
  return bound //11.返回绑定函数  返绑
}

function num(n1, n2) {
  console.log(this)
  console.log(`num1: ${n1}, num2: ${n2}`)
}

let tmp = num.myBind({}, 10);
tmp(20)

function Person(name, age) {
  this.name = name;
  this.age = age;
  console.log(this)//构造函数this指向其实例
  console.log(`name: ${this.name}, age: ${this.age}`)
}

let createPerson = Person.myBind({})
createPerson('test', 30)

标签:function,函数,实现,bind,age,调用者,let,name
From: https://www.cnblogs.com/idrinkmilk/p/16840297.html

相关文章