手写实现 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))
  }
 }

猜你喜欢

转载自blog.csdn.net/Beth__hui/article/details/112566120