this指向问题你真的彻底掌握了吗?

225 阅读3分钟

在前端的面试中,this指向与面向对象是必考题,也是日常开发中绕不开的话题,很多前端新手总感觉this指向变化莫测,琢磨不透;也有很多前端老鸟时常在this指向这里掉坑,本文主要围绕 this指向探讨一下,看看你是否真的彻底掌握了。

全局作用域中

我们可以直接在全局中向控制台打印 this,查看指向;

  1. 在浏览器中执行,会输出
console.log(this)  // 输出 window
  1. 在 node 中执行,会输出
console.log(this)  // 输出 {}

可以看出在 node 环境中输出了一个空对象,可以进一步测试

console.log(this === module.exports)  // 输出 true

结论:全局作用域中,在浏览器执行 this 指向的是 window;在 node 中执行,this 指向的是 module.exports。

函数中的 this 指向

按函数不同的使用场景,归纳为以下几种情况,分别举例进行说明。

1. 事件处理函数

设置一个简单的场景,有两个按钮,点击按钮,可以让按钮背景色变成红色,两个按钮互不影响

...
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
....
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");

btn1.onclick = changeBgColor;
btn2.onclick = changeBgColor;

function changeBgColor() {
  this.style.backgroundColor = "red";
}

结论:此时 this 指向的是调用它的 DOM 对象。

2. 全局作用域中的普通函数

  1. 在普通模式下直接调用 fn(),this 会指向 window;
function fn() {
  console.log(this);
}

fn();             // 输出 window
window.fn();      // 输出 window
  1. 在严格模式下调用,this 指向的是 undefined,如下:
'use strict'

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

fn();             // 输出 undefined
window.fn();      // 输出 window

结论:谁调用指向谁,严格模式下,函数没有被 window 显示调用,会指向 undefined。

3. 对象中的方法

var obj = {
  a: 10,
  b: function() {
    console.log(this);
  }
}

obj.b();          // 输出 {a:10, b: f}, 即对象 obj
window.obj.b();   // 输出 {a:10, b: f}, 即对象 obj

var c = obj.b;
c();             // 输出 window
window.c();      // 输出 window

结论:如果函数被多层对象包含,当被最外层调用时, this 指向的仍是它上一层对象。

4. 构造函数

function Fn(age) {
  this.age = age
  console.log(this);
}

var obj = new Fn(31);  // 输出 Fn {a:31},即新创建的对象

# 有种特殊情况,当构造函数中存在 return 时

function Fn(argu) {
  this.age = 10;
  return argu
}
// 返回个空字符传
 var obj1 = new Fn('');
 console.log(obj1.age); // 输出 10

// 返回个对象
var obj2 = new Fn({});
console.log(obj2.age); // 输出 undefined

// 返回 null
var obj3 = new Fn(null);
console.log(obj3.age); // 输出 10

结论:在构造函数中如果return 一个对象,this 指向返回的的对象,return null 和 非对象 及没有显式 return 时,则 this 指向 new 新创建的对像。

5. 箭头函数

var obj1 = {
  a: 10,
  b: function() {
    console.log('普通函数:', this)
  }
}

var obj2 = {
  a: 20,
  b: () => {
    console.log('箭头函数:', this)
  }
}

obj1.b();  // 输出 {a:10, b:f} 即 obj1对象
obj2.b();  // 输出 window 对象

结论:箭头函数本身是没有 this 和 arguments 的,在箭头函数中引用 this 实际上调用的是定义上一层作用域的 this ,这里强调一下是上一层作用域,因为对象是不能形成独立的作用域。