foreach可通过第二个参数thisarg指定回调函数的this值,如obj.scores.foreach(callback, obj);箭头函数无法通过thisarg改变this,因其继承外层作用域this。

JavaScript 中 forEach 可以通过传入第二个参数来指定回调函数内部的 this 值,这个参数会作为回调执行时的上下文对象。
语法结构
array.forEach(callback, thisArg)
-
callback:每次遍历元素时调用的函数,接收三个参数:
currentValue、index、array -
thisArg(可选):执行
callback时用作this的值。如果不传,非严格模式下为全局对象(如window),严格模式下为undefined
实际用法示例
假设有一个对象想在遍历时访问自身属性:
const obj = {
name: 'Alice',
scores: [85, 92, 78],
printScores() {
this.scores.forEach(function(score) {
console.log(`${this.name}: ${score}`);
}, this); // 关键:把 obj 作为 thisArg 传入
}
};
obj.printScores();
// 输出:
// Alice: 85
// Alice: 92
// Alice: 78
常见误区提醒
- 箭头函数不能通过
thisArg改变this,因为它不绑定自己的this,而是继承外层作用域的this - 如果回调里用了普通函数但没传
thisArg,this默认不是外层对象,容易报错或取到意外值 - 传入
null或undefined在严格模式下会让this保持为undefined;非严格模式下会被自动转为全局对象
替代写法对比
除了用 thisArg,也可以用以下方式达到类似效果:
- 用箭头函数(隐式绑定外层
this):this.scores.forEach((score) => console.log(`${this.name}: ${score}`)) - 用
bind:<pre class="brush:php;toolbar:false;">this.scores.forEach(function(score) { ... }.bind(this))</pre> - 用变量暂存:
const self = this; this.scores.forEach(function(score) { console.log(`${self.name}: ${score}`); })
其中直接传 thisArg 最简洁、语义最清晰。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











