javascript this是什么_它的指向规则如何确定

this是运行时绑定的引用,值取决于函数调用方式:独立调用指向全局对象(严格模式为undefined),对象方法调用指向该对象,new调用指向新实例,call/apply/bind显式指定,箭头函数继承外层this。

this 是 JavaScript 中的一个关键字,它不是一个固定值,而是一个在函数执行时才确定的**运行时绑定**的引用,指向当前函数被调用时所处的**执行上下文对象**。它的值不取决于函数如何定义,而取决于函数**如何被调用**。

普通函数调用(非严格模式)

当函数独立调用(即不通过对象属性、new 或 call/apply/bind 调用)时,this 指向全局对象:

  • 浏览器中是 window
  • Node.js 中是 global

例如:

function foo() { console.log(this); }
foo(); // window(浏览器)

作为对象方法调用

当函数作为对象的属性被调用时,this 指向该对象(即“点号左边的对象”):

const obj = {
  name: 'Alice',
  say() { console.log(this.name); }
};
obj.say(); // 'Alice' → this 指向 obj

注意:只看调用时的写法,和函数定义位置无关;若把方法赋给变量再调,this 会丢失(变*局对象或 undefined)。

构造函数调用(new)

使用 new 调用函数时,JavaScript 引擎会创建一个新对象,并将 this 绑定到这个新对象上:

function Person(name) {
  this.name = name; // this 指向新创建的实例
}
const p = new Person('Bob'); // p.name === 'Bob'

显式绑定(call / apply / bind)

可通过 callapplybind 显式指定 this 的值:

  • func.call(obj, arg1, arg2) —— 立即执行,this 设为 obj
  • func.apply(obj, [arg1, arg2]) —— 同上,参数传数组
  • func.bind(obj) —— 返回新函数,永久绑定 this 为 obj

bind 生成的函数无法再被 call/apply 覆盖(硬绑定优先级最高)。

箭头函数没有自己的 this

箭头函数不绑定 this,它会**沿作用域链向上查找外层普通函数的 this 值**(词法绑定):

const obj = {
  name: 'Charlie',
  regular() { console.log(this.name); },
  arrow: () => { console.log(this.name); } // this 是外层作用域的 this(通常是 window)
};
obj.regular(); // 'Charlie'
obj.arrow();   // undefined(因为外层 this 不是 obj)

因此箭头函数适合避免 this 失去上下文的场景(如事件回调、定时器),但不能用作构造函数或需要动态 this 的方法。

严格模式下的普通调用

在严格模式下,独立调用函数时 this 不再自动绑定到全局对象,而是保持为 undefined

'use strict';
function foo() { console.log(this); }
foo(); // undefined(不是 window)

这有助于提前发现 this 绑定错误。

优先级顺序(从高到低)

当多种规则同时存在时,this 的最终指向由以下优先级决定:

  • new 绑定 > 显式绑定(call/apply/bind) > 隐式绑定(对象方法) > 默认绑定(独立调用)
  • 箭头函数不参与该链条,它直接继承外层 this

理解 this 的关键是:别猜定义,盯住调用方式。每次看到函数执行,先问一句——“它是怎么被调用的?”