• this 关键字


    在 浏览器(chrome  83.0.4103.97(正式版本) (64 位))环境下测试 this 关键字

    匿名函数中的 this

    <script>
      console.log(this); // #1
      var brand = 'bmw';
      function Car(brand) {
        this.brand = brand;
        this.color = '';
        this.speed = 0;
      }
      Car.prototype.getBrand = function () {
        console.log(this); // #2
        return function () {
          console.log(this); // #3
          return this.brand;
        };
      };
      let car = new Car('ford');
      console.log(car.getBrand()());
    </script>
    

    可以发现

    1. 浏览器环境下的 this 指的是 window 对象:#1
    2. 匿名函数中的 this 指向 window 对象:#3,所以最后的 console: car.getBrand() 返回 bmw
    3. 命名函数的 this 指向函数所属的对象:#2

    var 与 this

    this 直接绑定的属性和 var 定义的属性指向的是同一个:

    <script>
      this.brand = 'benz';
      var brand = 'bmw';
      console.log(this.brand); // bmw
    </script>
    
    <script>
      var brand = 'bmw';
      this.brand = 'benz';
      console.log(this.brand); // benz
    </script>
    

    let 与 this

    和 var 不同,this 无法访问 let 定义的属性

    <script>
      this.brand = 'benz';
      let brand = 'bmw';
      console.log(this.brand); // benz
    </script>
    
    <script>
      let brand = 'bmw';
      this.brand = 'benz';
      console.log(this.brand); // benz
    </script>
    
    <script>
      let brand = 'bmw';
      // this.brand = 'benz';
      console.log(this.brand); // undefined
    </script>
    

    箭头函数与 this

    参考:
    https://es6.ruanyifeng.com/#docs/function
    https://www.cnblogs.com/vajoy/p/4902935.html

    箭头函数内的 this 对象指的是定义时的对象,是固定的,不会具有歧义性。
    里面举了很多例子,我觉得下面这一个可以很好的表达这种特点。

    // ES6
    function foo() {
      setTimeout(() => {
        console.log('id:', this.id);
      }, 100);
    }
    
    // ES5
    function foo() {
      var _this = this;
      setTimeout(function () {
        console.log('id:', _this.id);
      }, 100);
    }
    
  • 相关阅读:
    nginx增加lua支持
    使用nginx+lua实现web项目的灰度发布
    amoeba学习
    信号有关的内容
    Linux系统的进程相关内容
    等待类型
    孤立用户故障排除
    恢复数据库
    执行计划之Insert,update,delete
    临时表和表变量
  • 原文地址:https://www.cnblogs.com/ainsliaea/p/13086681.html
Copyright © 2020-2023  润新知