zoukankan      html  css  js  c++  java
  • 不同场景,this 的指向问题汇总

     定义:A property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.(this属于执行环境的一个属性,在非严格模式中指代对象,在严格模式中指代任何值)

    1.在全局环境中,this指向全部对象

    console.log(this === window) // 浏览器环境中window是全局对象

    2.在函数中,this指向函数的调用者,如果函数是直接执行的,那this默认指向全局对象

    function test() {
      return this
    }
    console.log(test() === window) // 直接执行函数,this默认指向全局对象
    
    
    let o = {}
    o._test = test
    console.log(o._test() === window)  // false
    console.log(o._test() === o)  // true

    3.在class中,this指定的是class实例,初始class的constructor函数将this默认绑定到了实例上,但是派生class的constructor函数并没有将this绑定到实例上,所以在调用this之前需要执行super函数,它的作用类似于 this = new (初始class),否则会报错误,如果派生class没有constructor函数,者可以不用调用super,简言之,super就是为了将初始class的实例绑定到派生class的this上。

    class Test {
      constructor() {
        this.a = 10
      }
    }
    class Test2 extends Test {
      constructor() {
        super()  // 没有这个就是报ReferenceError
        this.a = 20
      }
    }
    console.log((new Test2()).a)  // 20

    4.通过call、apply或者bind可以改变this的指向,详情链接

    5.在箭头函数中,this永远指向函数创建时的执行环境

    const test = () => this
    const o = {}
    o._test = test
    // test是在全局环境中创建的,所以一直都是指向window
    console.log(o._test())  // window

      箭头函数在对象中:

    const o = {
      test: function() {
        return (() => this)
      }
    }
    console.log(o.test()() === o) // true

    6.当函数作为对象的方法调用的时候,this指向调用此方法的对象。 (1.在原型链上,继承来的方法如果有this,那它指向继承此方法的对象;链接2.对象中的get或者set方法也是一样的道理。链接)

    function f() {
      return this.val;
    }
    const o = {
      val: 10
    }
    o._f = f;
    console.log(o._f()) // 10  

     7.在构造函数中,this指向被构造出来的新对象

    function test() {
      this.a = 10;
    }
    const o = new test()
    console.log(o.a) // 10

    8.在DOM事件处理函数中,this指向e.currentTarget,也就是当前绑定事件的元素对象,代码演示

  • 相关阅读:
    C语言 · 阶乘计算 · 基础练习
    C语言 · 查找整数 · 基础练习
    UML课程复习重点
    运维参考
    mysql语法总结
    Python杂篇
    Python练习题
    Python参考
    k8s中ipvs和iptables选择
    安装cni网络插件-非必须
  • 原文地址:https://www.cnblogs.com/re-doc/p/14073068.html
Copyright © 2011-2022 走看看