关于this指向

169 阅读1分钟

this 的值不是在函数定义时确定的,而是在函数被调用时绑定的,它的指向完全取决于函数的调用方式。

1. 默认绑定

独立函数调用(无法应用其他规则时)时,this 指向全局对象(在浏览器中是 window,在 Node.js 中是 global)。在严格模式 ('use strict') 下,this 为 undefined

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

showThis(); // 浏览器中输出: Window {...} (非严格模式)
            // 严格模式下输出: undefined

var a = 1;
function foo() {
  console.log(this.a);
}
foo(); // 输出: 1 (因为 this 指向 window,window.a = 1)

2. 隐式绑定

当函数作为一个对象的方法被调用时,this 指向调用这个方法的那个对象

const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // 输出: "Hello, my name is Alice"
                // 因为 greet 是 person 的方法,所以 this 指向 person

隐式丢失:这是一个常见的坑。当方法被赋值给另一个变量或作为回调函数传递时,会丢失原来的 this 绑定,退回到默认绑定规则。

const greetFunc = person.greet; // 将方法赋值给一个变量
greetFunc(); // 输出: "Hello, my name is " (name 是 undefined)
             // 此时是独立函数调用,this 指向全局(或 undefined)

// 作为回调函数
setTimeout(person.greet, 100); // this 同样丢失!

3. 显式绑定

也就是使用call、aplly、bind显示指定this的指向。

4.new 绑定

使用 new 关键字调用函数(构造函数)时,this 会绑定到新创建的那个实例对象上。

function Person(name) {
  // this = {}; (JS引擎隐式完成)
  this.name = name;
  this.sayHello = function() {
    console.log(`Hello from ${this.name}`);
  };
  // return this; (JS引擎隐式完成)
}

const alice = new Person('Alice');
alice.sayHello(); // 输出: "Hello from Alice"
// this 指向新创建的 alice 实例

5.箭头函数

ES6 的箭头函数是上述规则的例外。它没有自己的 this,它的 this 是继承自它定义时所处的外层(函数或全局)作用域的 this。这意味着箭头函数内的 this 是固定的,不会被调用方式改变。

const obj = {
  value: 42,
  regularFunc: function() {
    console.log('Regular:', this.value); // this 指向 obj
  },
  arrowFunc: () => {
    console.log('Arrow:', this.value); // this 继承自外部,可能是 window 或 undefined
  }
};

obj.regularFunc(); // 输出: "Regular: 42"
obj.arrowFunc();   // 输出: "Arrow: undefined" (假设外层是全局作用域,如果是在浏览器环境,且定义有value变量 var value = 1,则此处会输出 Arrow: 1)

// 箭头函数解决回调中 this 丢失的问题
const otherObj = {
  value: 'Hi',
  init: function() {
    // 箭头函数这里的 this 继承自 init 函数,而 init 的 this 由隐式绑定指向 otherObj
    setTimeout(() => {
      console.log(this.value); // 输出: "Hi"
    }, 100);
  }
};
otherObj.init();