在js函数中关于this指向问题及call()、apply()、bind() 的用法

1.在js函数中关于this指向问题 

      var name = "张三";
      var obj = {
        name: "李四",
        es5fun: function () {
          console.log(this);
        },
        es6fun: () => {
          console.log(this);
        },
      };
      obj.es5fun(); //obj
      obj.es6fun(); //window
      console.log(this); //window

在ES5中,函数作为对象的方法调用时,this指向的是调用的对象;

在ES6的箭头函数中,箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时,它所处的对象(宿主对象),而不是执行时的对象, 如果没有,就会一层层网上找,直到window。

2.call()、apply()、bind() 的用法

      var obj = {
        name: "李四",
        age: 99,
        myfun: function () {
          console.log(this.name + "年龄" + this.age);
        },
      };
      var otherObj = {
        name: "yasuo",
        age: 4,
      };

      obj.myfun(); //李四年龄99
      obj.myfun.call(otherObj); //yasuo年龄4
      obj.myfun.apply(otherObj); //yasuo年龄4
      obj.myfun.bind(otherObj)(); //yasuo年龄4

call()、apply()、bind() 都是用来重定义 this 这个对象的!换句话说也可以是一个对象调用其他对象方法的方法

对比call 、bind 、 apply 传参情况

var obj = {
      name: "李四",
      age: 99,
      myfun: function (kill, death) {
        console.log("名称:" + this.name + " 年龄:" + this.age + "  杀人数:" + kill + "  死亡:" + death);
      },
    };
    var otherObj = {
      name: "yasuo",
      age: 4,
    };

    obj.myfun.call(otherObj, '0', '10'); //名称:yasuo 年龄:4  杀人数:0  死亡:10
    obj.myfun.apply(otherObj, ['0', '10']); //名称:yasuo 年龄:4  杀人数:0  死亡:10
    obj.myfun.bind(otherObj, '0', '10')(); //名称:yasuo 年龄:4  杀人数:0  死亡:10

   第一个参数:

     call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象

   第二个参数:

     call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,直接放到后面

     apply 的所有参数都必须放在一个数组里面传进去 

     bind 除了返回是函数以外,它 的参数和 call 一样

     当然,三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object 等

猜你喜欢

转载自blog.csdn.net/qq_41111677/article/details/108281365