this指向问题

this指向
  1. 在浏览器环境this指向window、nodeJs环境下this指向global

    function bar(){console.log(this)}
    window.bar() //window
    
  2. 方法调用中谁调用this指向谁

    const person={run(){console.log(this)} }
    person.run() //person调用了run this指向了person
    //事件绑定
    btn.addEventListener(type,function(){console.log(this)})
    //this指向btn
    
  3. 箭头函数的this指向父级作用域this

  4. new可以改变改变this指向,this指向内存中实例对象

  5. call、apply可以改变this的指向(了解)

    1. call用法

      1. 所有函数中内置了call函数

      2. call函数动态指定了当前函数调用权利

      3. 格式:fn.call(ObjectTarget,实参1,实参2,…)
        const obj={name:'wt'} function fn(a){console.log(${this.name} is ${a})} fn.call(obj,'good')

      4. 主要作用:改变构造函数中this的指向

      function Father(name,age){
      this.name=name;
      this.age=age;
      }
      function Son(name,age){
      Father(this,name,age) //给this赋值
      }
      
    2. apply用法

      1. apply用法和call同
      2. apply调用格式:fn.apply(ObjectTarget,数组)
      3. 传递参数为数组时,可以直接使用apply
        const arr = [2,4,9]; Math.max.apply(Math,arr) //没有使用this
    3. bind用法

      1. bind方法改变内部this指向,但不会立即调用函数,返回一个改变this指向和初始化参数构造的原函数拷贝

      2. 应用:如果有的函数不需要立即调用,但是又想改变这个函数内部指向 :按钮点击置灰,3s后开启

      btn.click=function(e){
      this.disable=true;
      setTimeout(fn.bind(this),3000)
      function fn(){
      this.disable=false;
      }
      }
      //bind方法绑定
      const o={name:'andy'}  function fn(){console.log(this.name)}
      const fCopy=fn.bind(o)
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值