1、this指向要素

  • this指向的只可能是对象
  • this指向谁取决于函数在哪调用
  • this指向的对象称为函数上下文,也叫函数的调用者

2、指向规律

方法中,this指向该方法的所属对象,如果单独使用,this表示全局对象;在函数中也是表示全局对象,但是在严格模式下,this是未定义的;在事件中则是接收事件的元素;类似call() 和 apply() 方法可以将 this 引用到任何对象

2.1 函数名()直接调用

  this指向window

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

  运行结果:

javascript中this的指向 js this指向问题_前端

2.2 方法中调用this

  在对象方法中,this指向调用它所在方法中的对象

var person = {
            firstName: "123",
            lastName: "456",
            myFunction: function () {
                return this.firstName + " " + this.lastName;;
            }
        };
        console.log(person.myFunction());

  运行结果:

javascript中this的指向 js this指向问题_visual studio code_02

2.3 单独使用this

  此时指向全局对象

var a=this;
   console.log(this);

  运行结果:

javascript中this的指向 js this指向问题_javascript_03

2.4 函数中使用this

  • 默认情况下
    this指向全局对象
function func() {
            return this;
        }
        console.log(func());

运行结果:

javascript中this的指向 js this指向问题_前端_04

  • 严格模式下

this显示未定义

"use strict";
        function func() {
            return this;
        }
        console.log(func());

  运行结果:

javascript中this的指向 js this指向问题_javascript_05

2.5 对象方法中绑定

this指向了person对象

var person = {
            firstName: "123",
            lastName: "456",
            id: 1234,
            myFunction: function () {
                return this;
            }
        };
        console.log(person.myFunction());

  运行结果:

javascript中this的指向 js this指向问题_javascript中this的指向_06

2.6 显式函数绑定

js中函数也是对象,对象就有方法,applycall就是函数对象的方法,他们允许切换函数执行的上下文环境,这种情况就被称为this绑定函数

var person1 = {
            FullName: function () {
                return this.firstName + " " + this.lastName;
            }
        }
        var person2 = {
            firstName: "A",
            lastName: "B"
        }
        console.log(person1.FullName.call(person2));

  运行结果:

javascript中this的指向 js this指向问题_javascript_07

3、箭头函数的this指向

  • 箭头函数本身没有作用域(无this)
  • 基本语法:参数=>函数体
  • this等同于上一层非箭头函数的this值或全局对象(window或undefined)

参考资料:this关键字