1. this
指向的不同
- 普通函数:
this
的指向在函数被调用时确定,取决于函数的调用方式。如果是作为对象的方法调用,this
指向该对象;如果是独立调用,在非严格模式下,this
指向全局对象(浏览器环境中是 window
),在严格模式下,this
指向 undefined
。
- 箭头函数:箭头函数没有自己的
this
,它的 this
继承自外层作用域(词法作用域),即定义箭头函数的地方的 this
。
2. 代码示例
// 普通函数
function ordinaryFunction() {
console.log(this);
}
ordinaryFunction(); // 在非严格模式下,输出全局对象(浏览器中是 window)
const obj = {
name: 'test',
method: function() {
console.log(this);
}
};
obj.method(); // 输出 obj 对象
// 箭头函数
const arrowFunction = () => {
console.log(this);
};
arrowFunction(); // 输出全局对象(浏览器中是 window),因为箭头函数继承了外层作用域的 this
const outerObj = {
name: 'outer',
inner: {
name: 'inner',
arrowMethod: () => {
console.log(this.name); // 这里输出 'outer',因为箭头函数继承了外层(outerObj 所在作用域)的 this
}
}
};
outerObj.inner.arrowMethod();