You need to enable JavaScript to run this app. JavaScript数组方法中thisValue参数的作用是什么?
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 14:27:02