在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() 

定义:

用来重定义(函数内部)this 这个对象的!换句话说也可以是一个对象调用其他对象方法的方法

不同点:

        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 、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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值