this的指向

this的指向:this的指向和它的调用方式有关
1.普通函数调用: 匿名函数调用 定时器的调用 此时this指向window
2.事件处理函数: this指向触发事件的事件源
3.开启严格模式的情况下: 普通函数的this指向undefined
4.对象中this:指向这个对象
5.方法调:用则指向方法的对象(谁调用指向谁)
6.构造函数中的this指向:新创建的实例对象 原型中的this也是指向实例对象
7.箭头函数没有this指向: 它的this指向和它的外层作用域中的this保持一致
8.上下文调用模式:call和apply方法中 this指向方法中的第一个参数 bind的方法中 this指向的是bind新创建的函数
复制代码
<body>
    <button>123</button>
    <script>
     
      //   "use strict";开启严格模式普通函数指向 undefined
      function fn() {
        console.log(this); //普通函数this指向window
      }
      fn();

      let fun = function () {
        console.log(this); //匿名函数中的this指向window
      };
      fun();

      setInterval(function () {
        // console.log(this);//定时器中的this指向window
      }, 1000);

      const btn = document.querySelector("button");
      btn.addEventListener("click", function () {
        console.log(this); //事件处理函数this指向触发当前事件的事件源<button>123</button>
      });

      let obj = {
        name: "zs",
        age: 17,

        sing() {
          console.log("闹闹 哄哄");
          console.log(this); //{name: 'zs', age: 17, sing: ƒ}对象中的this指向当前对象
        },
      };
      obj.sing();
      // =====================
      function Star(name, age) {
        (this.name = name), (this.age = age);
        console.log(this); //{name: 'hh', age: 17}  构造函数中的this指向实例化对象
      }
      const zjl = new Star("hh", 17);
      Star.prototype.sing = function () {
        console.log(this); //{name: 'hh', age: 17}  构造函数原型方法的调用this也指向实例化对象
      };
      zjl.sing();

      //=======================
      const obj1 = {
        uname: "zs",
        sing: () => {
          console.log(this); //指向windod(箭头函数中没有this指向 和他当前所处环境的外层作用域中的this指向一致)
        },
      };
      obj1.sing();
    </script>
  </body>
复制代码

 

posted @   噢噢噢J  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示