102. JavaScript 中 this
的指向问题
-
this
的定义:
this
是 JavaScript 中的一个关键字,它的值取决于函数调用的上下文。this
的指向在不同的调用方式下会有所不同。 -
this
指向的几种情况:-
全局作用域下:在全局作用域中,
this
指向window
对象(严格模式下为undefined
)。console.log(this === window); // true
-
对象方法调用:当
this
出现在对象的方法中时,this
指向调用该方法的对象。const obj = { name: 'Junjie', getName() { console.log(this.name); } }; obj.getName(); // 输出 'Junjie'
-
构造函数调用:在构造函数中,
this
指向新创建的实例对象。function Person(name) { this.name = name; } const person = new Person('Hu'); console.log(person.name); // 输出 'Hu'
-
箭头函数:箭头函数没有自己的
this
,它的this
是在定义时继承自外部上下文的this
。const obj = { name: 'Arrow', getName: () => { console.<
-