JavaScript数组方法中thisValue参数的作用是什么?
JavaScript数组map/filter方法thisValue参数作用
thisValue 是可选参数,作用是自定义回调函数内部 this 关键字的指向。
- 不传入该参数时,非严格模式下回调内部的
this会指向全局对象(浏览器环境为window,Node.js 环境为global),严格模式下this为undefined - 传入该参数时,回调函数内部的
this会固定指向你传入的这个对象,不会受调用位置影响
实际使用示例
// 定义一个用来计算折扣的对象 const discountCalculator = { discount: 0.8, getFinalPrice(originPrice) { return originPrice * this.discount; } }; const originPrices = [100, 200, 300]; // 把discountCalculator作为thisValue传入map方法 const finalPrices = originPrices.map(function(price) { // 这里this直接指向discountCalculator对象,可以直接调用它的方法和属性 return this.getFinalPrice(price); }, discountCalculator); console.log(finalPrices); // 输出 [80, 160, 240]
如果上面的示例不传入 discountCalculator 作为 thisValue,回调内部的 this 无法找到 getFinalPrice 方法,会直接抛出错误。
注意事项
如果你使用箭头函数作为回调,该参数会完全失效。因为箭头函数没有自己独立的 this 上下文,它的 this 继承自外层作用域,无法通过 thisValue 手动修改。
内容的提问来源于stack exchange,提问作者Vansh Bhardwaj
相关产品推荐
相关产品推荐

