call、apply 及 bind、 callee与caller函数

所有内容均不是原创,单纯之前学习时做的笔记。内容结合了非常多的文章视频,很多已经记不清参考的哪里了,所以就不加参考说明了。

call、apply 及 bind 函数

  • callapply:改变this的指向,让新的对象可以执行该函数,并能接受参数

  • bind 方法也改变this指向后返回一个新的函数,需要再次调用。

  • callapply唯一的区别是apply的第二个参数要用数组来传值

    • function Car(brand, color){
        this.brand= brand;
        this.color=color;
      }
      var newCar = {};
      var newCar2 = {};
      //Car.call(newCar,'Benz','red');
      Car.apply(newCar, ["Benz","red"]);
      Car.bind(newCar2,'Benz','red')();
      ​
      console.log (newCar);//{brand: 'Benz', color: 'red'}
      console.log(newCar2);//{brand: 'Benz', color: 'red'}
      

手写 bind 函数

Function.prototype.myBind = function (context) {
  const _this = this
  const args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}

callee、caller

  • callee: 返回arguments所指向的函数本身

    • 需要实现一个递归的自执行函数的时候可以使用callee去获取这个函数
    • function text(a,b,c){
        console.log(arguments.callee);//text函数
        //函数的length属性是形参的个数,arguments.length是实参的个数
        console.log(text.length);//3
        console.log(arguments.length);//2
      }
      text(1,2)
      
  • caller:返回当前被调用函数的函数引用

    • text1();
      function text1(){
        text2(); 
      }
      function text2(){
        console.log(text2.caller);//text1函数
      }
      
  • 严格模式下callee、caller都不能被调用