Implementar call y aplicar y vincular a mano

1. Uso de call and bind and apply

Primero defina un objeto y una función

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

Ahora, si simplemente llama a getValue normalmente, esto se refiere a la ventana,
pero si es la siguiente llamada, esto se refiere al objeto a.

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

En segundo lugar, la diferencia
Sabemos que llamar y aplicar pueden cambiar este punto de la ejecución de la función,
pero tanto llamar como aplicar ejecutan la función inmediatamente, y bind vincula este punto al objeto especificado, y devuelve la función y mantiene este punto a este objeto.

Tres, implementar la llamada y aplicar a mano

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

Cuarto, implemente atar a mano

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

Supongo que te gusta

Origin blog.csdn.net/Beth__hui/article/details/112566120
Recomendado
Clasificación