JavaScript this指向 几种情况

  • 【情况1:普通函数内部的this指向window】
  • 【情况2:定时器内部的this指向window】
  • 【情况3:在构造函数中,this指向当前创建的对象】
  • 【情况4:对象的方法中,this指向调用者】
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    // this,一定是函数内部研究
    // this在函数内部的指向谁?
    // this在函数内部的指向,不是在函数定义时决定的,而是在调用时决定的。

    // 【情况1:普通函数内部的this指向window】
    function fn() {
      console.log(this);
    }
    fn();

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

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


    // 【情况2:定时器内部的this指向window】
    setTimeout(function () {
      console.log(this);
    }, 10);

    // 【情况3:在构造函数中,this指向当前创建的对象】
    function Person(name, age) {
      this.name = name;
      this.age = age;
      console.log(this);
    }
    var p1 = new Person('zs', 10);

    // 【情况4:对象的方法中,this指向调用者】
    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    Person.prototype.sayHi = function () {
      console.log(this);
    };
    var p1 = new Person('zs', 10);
    var p2 = new Person('ls', 20);


    // 【情况5:在事件处理程序中,this指向事件源】
    document.onclick = function () {
      console.log(this);
    };
    // 本质上就是浏览器自动的执行了 document的onclick方法
    console.dir(document);
  </script>
</body>

</html>
```javascript
发布了63 篇原创文章 · 获赞 5 · 访问量 826

猜你喜欢

转载自blog.csdn.net/wuj1935/article/details/102982344