You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组挂载自定义箭头函数方法时this指向异常的技术咨询

给数组添加自定义方法时的this指向问题

嘿,这个问题其实是箭头函数的this特性在搞鬼,咱们来捋清楚:

问题根源:箭头函数的this绑定

你用箭头函数定义arr.hello的时候踩了个小坑——箭头函数没有自己的this绑定,它的this是直接继承自函数定义时所在的词法环境,而不是调用时的上下文。在你的代码里,定义箭头函数的环境如果是全局作用域(或者严格模式下的空对象),那this就会指向那里,所以调用arr['hello']()时,自然拿不到arr本身,输出空对象也就不奇怪了。

解决方案:改用普通函数

如果想要this指向调用这个方法的数组arr,你得用普通函数来定义这个自定义方法。因为普通函数的this是由调用方式决定的:当你通过arr.hello()或者arr['hello']()调用时,this就会绑定到arr上。

修正后的代码如下:

const arr = [1,2,3,4]; 
arr.hello = function() {return this}; 
console.log(arr['hello']()); // 输出 [1,2,3,4]

满足你的需求:获取arr[0]

现在this已经指向arr了,你只需要在方法里返回this[0]就能拿到数组的第一个元素:

const arr = [1,2,3,4]; 
arr.hello = function() {return this[0]}; 
console.log(arr['hello']()); // 输出 1

另外补充个小技巧:如果想让所有数组都拥有这个方法,你可以扩展Array.prototype,不过要注意别随便污染全局原型链,最好先检查方法是否存在:

// 给所有数组添加hello方法
if (!Array.prototype.hello) {
  Array.prototype.hello = function() {
    return this[0];
  }
}

const arr1 = [1,2,3];
const arr2 = [5,6,7];
console.log(arr1.hello()); // 1
console.log(arr2.hello()); // 5

内容的提问来源于stack exchange,提问作者user13269256

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:22:51