Implement call and apply and bind by hand

1. Use of call and bind and apply

First define an a object and a function

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

Now if you simply call getValue normally, the this refers to the window
but if it is the following call, this refers to the a object.

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

Second, the difference
We know that call and apply can change the this point of the function execution,
but both call and apply execute the function immediately, and bind binds the this point to the specified object, and returns the function and maintains this point to this object .

Three, implement call and apply by hand

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;
  }

Fourth, implement bind by hand

 /// 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))
  }
 }

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/112566120