js bind

JS Bind 方法详解

js bind 理解笔记

原文链接: https://blog.youkuaiyun.com/qq_39148344/article/details/90173640看的他的 我只是加强一下印象
function.prototype.bind():
bind():方法主要就是将函数绑定到某个对象上 ,
例如:f.bind(obj),实际上可以理解为 obj.f(),这时f函数体内的this指向obj;

  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);//this指向window 没有c这个属性所以输出 undefined
      }
      func();
    },
    c: 'hello'
  }
  a.b(); 
  console.log(a.c); 

那么问题来了当我们希望func()他的输出的值就是为hello怎么办

方法一 改变this的值

  var a = {
    b: function() {
    var _that=this//通过赋值的方式将this赋值给that
      var func = function() {
      console.log(_that.c)
      }
      func();
    },
    c: 'hello'
  }
  a.b(); //hello
  console.log(a.c); //hello

方法二:绑定this的值发生改变

//使用bind方法1
  var a = {
    b: function() {
      var func = function() {
      console.log(this.c)
      }.bind(this)
      func();
    },
    c: 'hello'
  }
  a.b(); //hello
  console.log(a.c); //hello
  //使用bind方法2
  var a = {
    b: function() {
      var func = function() {
      console.log(this.c)
      }
      func.bind(this)();
    },
    c: 'hello'
  }
  a.b(); //hello
  console.log(a.c); //hello

这里我们以a.b()的形式去执行a对象中的b这个函数,是经过对象a的所以当我们来执行a对象中b函数的时候找this就会先找到a对象所以在a对象中的b这个函数中的this为a对象,所以这个时候bind,绑定的this也就是为a对象了

   c='haha'
 var a = {
      b: function () {
        console.log(this);//window
        var func = function () {
          console.log(this.c);//haha
        }.bind(this);
        func();
      },
      c: 'hello'
    }
  var d=a.b;
  d() 

这里我们以d()的形式去执行a对象中的b这个函数吗,因为d()的执行的时候由于没人应用this默认为window,所以在a对象中的b这个函数中的this为window,所以不这个时候bind,绑定的this也就是为window了

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值