this 的指向,可以分为两个大类:

  • 函数外部:永远指向全局对象(window);
  • 函数内部,分为两种情况:
    • 箭头函数:箭头函数中没有 this,如果要在箭头函数中使用 this,实际上使用的就是箭头函数所在作用域中的 this。
    • 非箭头函数:谁调用的该函数,函数中的 this 就指向谁;

      函数内部的 this

      1、普通函数

      普通函数,就是函数本身创建时不是箭头函数,调用时直接通过 函数名() 调用,这样的就属于普通函数。
      1. function foo() {
      2. console.log(this); // window
      3. }
      4. foo();
      结论:普通函数的 this 指向 window。

      2、对象方法

      1. const student = {
      2. name: '张三',
      3. sayHello: function () {
      4. console.log(this);
      5. }
      6. }
      7. const person = {
      8. name: '李四'
      9. };
      10. person.sayHello = student.sayHello;
      11. student.sayHello(); //student{}
      12. person.sayHello(); //person{}
      结论:对象方法的 this,指向调用该方法的对象。

      3、事件处理函数

      1. const father = document.getElementById('father');
      2. father.addEventListener('click', function() {
      3. console.log(this); // father
      4. })
      结论:原生 JS 事件处理函数中的 this,指向的是绑定事件的元素节点。

      4、构造函数、class

      1. function Person() {
      2. console.log(this);
      3. }
      4. const person = new Person(); // person
      5. class Student {
      6. constructor() {
      7. console.log(this);
      8. }
      9. }
      10. const student = new Student(); // student
      结论:构造函数或 class 中的 this,指向 new 出来的实例对象。

      5、箭头函数

      1. const student = {
      2. name: '张三',
      3. sayHello: function() {
      4. const foo = () => {
      5. console.log(this);
      6. }
      7. foo();
      8. }
      9. }
      10. student.sayHello(); //student{}
      结论:箭头函数中没有 this。如果要在箭头函数中使用 this,实际上使用的就是箭头函数所在作用域中的 this。

      6、jquery 事件处理函数

      1. $('#father').on("click", function() {
      2. console.log($(this));
      3. })
      结论:jQuery 事件处理函数中的 this,指向的是触发事件的元素(表示有可能是子元素等)。