深入理解this指向问题

2024-06-18 00:20:05

浏览:73

评论:0

this 的值取决于它出现的上下文:对象、函数、类。因此我们通过分析对象、函数、类来深入理解this。mozilla文档

对象中this指向

this永远指向调用它的对象,默认指向全局对象。

全局对象

  • 浏览器环境中,全局下的 this 默认指向到 window 对象。
  • Node.js环境中,全局下的 this 默认指向到 global 对象。

普通对象

var str = "https://tool.vscing.com";
const obj = {
  str: "tool.vscing.com",
  getStr() {
    console.log(this.str);
  }
}
obj.getStr(); // tool.vscing.com

var strFun = obj.getStr;
strFun(); // https://tool.vscing.com

函数中this指向

普通函数

function 关键词定义的函数,this值在运行时确定,通常在非严格模式下指向全局对象(在浏览器中是window),在严格模式下或非全局上下文中指向调用函数的对象。 普通函数有arguments参数、可以作为构造函数、能被new、有原型(Prototype)、可以定义为Generator函数、使用call,apply,bind可以改变this指向。

var str = "https://tool.vscing.com";

function domain () {
  console.log(this.str);
}
domain(); // https://tool.vscing.com

var obj = {
  str: "tool.vscing.com",
  domain
}

obj.domain(); // tool.vscing.com

箭头函数

=> 语法定义的函数,不会创建自己的this上下文,内部的this就是其定义时所在的上下文的this。 箭头函数没有arguments参数、无法作为构造函数,不能被new、this取决于上下文,本身没有this、使用call,apply等无法改变this指向。

var str = "https://tool.vscing.com";
const domain = () => {
  console.log(this.str);
}
domain(); // https://tool.vscing.com

var obj = {
  str: "tool.vscing.com",
  domain: domain
}

obj.domain(); // https://tool.vscing.com

类中this指向

this 默认指向类实例对象。如果使用了箭头函数,this 会继承外围作用域中的 this。

var str = "https://tool.vscing.com";

class VClass {
  constructor() {
    this.str = 'tool.vscing.com';
  }
 
  // 使用常规函数声明的方法,this 指向实例对象
  getStr() {
    console.log(this.str);
  }
 
  // 使用箭头函数声明的方法,this 继承自外围作用域
  getArrowStr = () => {
    console.log(this.str); 
  };
}
 
const instance = new VClass();
instance.getStr(); // tool.vscing.com
instance.getArrowStr(); // https://tool.vscing.com

修改this指向

  • 可以通过call(), apply() 和 bind() 方法修改函数内 this 的指向。参考之前文章