手写实现 call 与 apply 与 bind

一、call 与 bind 与 apply 的使用

先定义一个 a对象 与 一个 函数

let a = {
   value: 1
 }
 function getValue(name, age) {
   console.log(name)
   console.log(age)
   console.log(this.value)
 }

现在 如果单纯的正常 调用 getValue , 其中的this是指向 window
但是 如果是以下调用 则 this指向 a对象。

getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])
getValue.bind(a)('yck', '24');

二、 区别
我们知道call和apply可以改变函数执行的this指向,
但是call和apply都是立即执行该函数,而bind是将this指向绑定到指定的对象上,并且返回函数并维持this指向这个对象。

三、手写实现call 与 apply

Function.prototype.myApply = function (context) {
 var context = context || window // 不传入第一个参数,那么默认为 window
  context.fn = this // this 指向方法的调用者; 这一步就是改变了this指向
  var result
  // 需要判断是否存储第二个参数
  // 如果存在,就将第二个参数展开
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}
  Function.prototype.myCall = function(context){
    var context = context || window;
    content.fn = this;
    var args = [...arguments].slice[1];
    var result = context.fn(...args);
    delete context.fn;
    return result;
  }

四、 手写实现bind

 /// bind 和其他两个方法作用也是一致的,只是该方法会返回一个函数。并且我们可以通过 bind 实现柯里化
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var args = [...arguments].slice(1); // 兼容传参数的形式 与 call一致; slice(1)就是去除了第一项
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) { // this 是 window
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
 }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值