• js中this指向 码农


    一、this指向

    原则是谁调用,就指向谁


    1:common function,
    this指向Window

    function fn(){
        console.log(this)
    }
    fn()

    //this-->Window

    2:Object function,
    this指向方法所属对象

    var o={
        fn:function(){
            console.log(this)
        }
    }    

    fn() //this-->o


    3:construct,this指向实例对象

    function Star(name,age){
        this.name=name;
        this.age=age;
    }

    Star.prototype.sing=function(){

      console.log(this)

    }

    let star=new Star('tom',18)

    star.sing();

    this-->star实例对象

    4:定时器,this指向Window

    setTimeout(
      function(){
        console.log(this)
      },1000
    )

    //this-->Window

    5:bind event function,
    this指向绑定事件元素

    document.body.onclick=function(){
      console.log(this)
    }

    //this-->element


    6:立即执行函数Immediately-Invoked Function Expression 即IIFE,
    this指向Window

    (function(){
      console.log(this)
    })()

    //this-->Window


    二、严格模式"strict"
    1:common function,
    this指向undefined

    'use strict'
    
    function fn()}
      console.log(this)
    }

    fn() //this-->undefined

    2:定时器,严格模式下this还是指向Window

    'use strict'
    
    setTimeout(
      function(){
        console.log(this)
      },1000
    )

    //this-->Window

    class A {
      constructor() {
      }
      handleClick() {
        console.log(this)
      }
    }
    
    var a = new A()
    a.handleClick() // this-->A实例 
    
    let b= a.handleClick
    b() // this-->undefined, 因为b是一个引用,不是实例调用,类中的方法开启了局部严格模式
    

     

    三、React 函件组件中的this

    this->undefined

    因为babel翻译的时候使用了严格模式

  • 相关阅读:
    HDU 2098 分拆素数和 数论
    CodeForces The Endless River
    CodeForces Good Words
    CodeForces A or B Equals C
    HDU 1251 统计难题 字典树/STL
    CSUOJ 1555 Inversion Sequence 线段树/STL
    OpenJudge P4979 海贼王之伟大航路 DFS
    敌兵布阵 线段树
    HDU 4004 The Frog's Games 二分
    HDU 2578 Dating with girls(1) 二分
  • 原文地址:https://www.cnblogs.com/dming4/p/16369421.html
Copyright © 2020-2023  润新知