js - 简单理解this的指向问题

首先要说的是,传统函数this指向调用者 箭头函数this指向声明时所处的对象。

1,普通函数中的this指向-> Window

 function fun1() {
     console.log("this:",this);
  }
  fun1()
  // 打印结果: this: Window顶层对象

2,严格模式下普通函数中的this指向-> undefined

JavaScript 除了提供正常模式外,还提供了严格模式(strict mode)。ES5 的严格模式是采用具有限制性> JavaScript 变体的一种方式,即在严格的条件下运行 JS 代码。

严格模式对正常的 JavaScript 语义做了一些更改:

  • 消除了 Javascript 语法的一些不合理、不严谨之处,减少了一些怪异行为。
  • 消除代码运行的一些不安全之处,保证代码运行的安全。
  • 提高编译器效率,增加运行速度。
  • 禁用了在 ECMAScript 的未来版本中可能会定义的一些语法,为未来新版本的 Javascript
    做好铺垫。比如一些保留字如:class, enum, export, extends, import, super 不能做变量名。
   // "use strict";//开启严格属性
   function fun1() {
       console.log("this:",this);
    }
    fun1()
    // 打印结果: this: undefined

3,事件函数中的this指向-> Window
点击事件里面的this指向是Window

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="demo">
        <button onClick='eventThis()'>事件中里面的this指向:</button>
    </div>
    <script>
  
        function eventThis(){
            console.log("普通事件中的this:",this);
            // 打印结果: this: Window顶层对象
        }
     </script>
</body>
</html>

3,构造函数以及类中的this指向 -> 实例化对象

在构造函数以及类中的this,构造函数配合 new 使用, 而 new 关键字会将构造函数中的 this 指向实例化对象,所以构造函数中的 this 指向 当前实例化的对象;

3.1 构造函数中的this指向如下:

1,创建一个构造函数:
 function UmbraFun(name, age) {
        this.name = name;
        this.age = age;
        this.say = function () {
          console.log('构造函数中的this指向:',this);
        };
      }
     2,进行实例化
      let Umbra = new UmbraFun('安柏',17)
      Umbra.say()
    打印结果:UmbraFun {name: '安柏', age: 17, say: ƒ}

3.2 类中的this指向如下:

/* 在构造函数以及类中的this,构造函数配合 new 使用, 
 而 new 关键字会将构造函数中的 this 指向实例化对象,所以构造函数中的 this 指向 当前实例化的对象 */
      class People {
        constructor() {
          console.log('构造器中的this:', this);
          // 打印结果  People
        }
        dance() {
          console.log('类中的this指向:', this);
        }
      }
      let Eula = new People();
      Eula.dance(); // 打印结果  People

4, 对象中的普通函数和箭头函数的指向:普通函数指向–>该对象,箭头函数指向–>父级的this指向

    /* 对象中的this指向 */
      let umbraObj = {
        name: '安柏',
        say: function () {
          console.log('对象中普通函数的this指向:', this);
          // 打印结果: {name: '安柏', say: ƒ, say2: ƒ}
        },
        say2: () => {
          console.log('对象中箭头函数的this指向:', this);
          // 打印结果: this: Window顶层对象
        },
      };
      umbraObj.say();  // {name: '安柏', say: ƒ, say2: ƒ}
      umbraObj.say2();  // this: Window顶层对象
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值