如何理解js中this指向:由执行上下文决定在执行时确定?

it2026-04-23  3

对于this指向的解释,在MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)中有这么一句话,

In most cases, the value of this is determined by how a function is called (runtime binding).

大概意思是说,this的值是由这个函数如何被调用来决定的。

我把它理解为: 函数定义的时候,this的指向是不确定的(函数体的代码主要是一些通用逻辑 - universal logic) 只有在真正调用的时候,才能确定this的指向(函数体的逻辑才被赋予了具体的含义 - specific meaning)


通过两个情形来理解

(注:以下的讨论都基于严格模式及普通函数。 全局环境中,在严格模式下, this指向undefined, 在非严格模式下,this指向window)

1. 一个函数在全局环境定义的

如果在全局环境中调用,this指向undefined

如果通过一个对象调用, this指向该对象

// 一个函数在全局环境定义的 function getValue () { console.log('this 指向', this); this && console.log('this.value:', this.value); } class A { constructor (value) { this.value = value; } getValueForA = getValue; } // 运行查看结果 console.log('***如果在全局环境中调用,this指向undefined***'); getValue(); console.log('***如果通过一个对象调用,this指向该对象***'); const a = new A('a'); a.getValueForA(); // a

以上代码的输出结果为:

2. 一个函数在类中定义的

如果在全局环境中调用,this指向undefined

如果通过一个对象调用,this指向该对象

// 一个函数在全局环境定义的 class A { constructor (value) { this.value = value; } getValueForA () { console.log('this 指向', this); this && console.log('this.value:', this.value); }; } // 运行查看结果 console.log('***如果通过一个对象调用,this指向该对象***'); const a = new A('a'); a.getValueForA(); // a console.log('***如果在全局环境中调用,this指向undefined***'); const getValue1 = A.prototype.getValueForA; const getValue2 = a.getValueForA; getValue1(); getValue2();

以上代码的输出结果为:


结论

函数定义就是定义,this的指向是不确定的,只有在真正调用的时候,才能确定this的指向。

即使是在类中定义的方法,它的this指向并不是确定指向该方法所在的对象,也是要等调用的时候才知道。

如果你理解了,你应该知道下面的这段代码,输出应该是什么了:

class A { constructor (value) { this.value = value; } getValueForA () { console.log('this 指向', this); this && console.log('this.value:', this.value); }; } class B { constructor (value) { this.value = value; } } // 运行查看结果 const a = new A('a'); const b = new B('b'); b.getValueForB = a.getValueForA; b.getValueForB();

输出结果:

最新回复(0)