- 函数表达式的
this
指向:
- 在函数表达式中,
this
的指向取决于函数的调用方式。
- 一般情况下,在全局作用域中调用函数,
this
指向全局对象(在浏览器中是window
,在Node.js中是global
)。
- 当函数作为对象的方法被调用时,
this
指向该对象。
- 示例代码:
// 全局作用域中的函数表达式
function funcExpression() {
console.log(this);
}
funcExpression(); // 在浏览器中输出 window 对象,在Node.js中输出 global 对象
const obj = {
name: 'example',
method: function() {
console.log(this.name);
}
};
obj.method(); // 输出 'example',这里的this指向obj对象
- 箭头函数的
this
指向:
- 箭头函数没有自己的
this
,它的this
指向定义时所在的作用域的this
,也就是词法作用域的this
。
- 示例代码:
const obj = {
name: 'example',
arrowMethod: () => {
console.log(this.name);
}
};
obj.arrowMethod(); // 输出 undefined,因为箭头函数的this指向定义时的作用域,这里是全局作用域,全局作用域中没有name属性
function outer() {
this.name = 'outer';
const arrow = () => {
console.log(this.name);
};
arrow(); // 输出 'outer',箭头函数的this指向定义时所在的outer函数的this
}
outer.call({}); // 输出 'outer',通过call改变outer函数的this指向空对象,箭头函数的this也跟着outer函数的this指向改变