'this'关键字在此方法中引用了什么

问题描述 投票:7回答:1

我对在这种情况下如何使用this关键字感到困惑。它被放置在带有参数回调的匿名函数中,然后使用它:callback(this[i], i, this)。这个练习没有深入,但据我所知,this指的是__proto__中的ar对象。为什么3个参数被放置在匿名函数的参数callback(this[i],i,this)and中它是如何在引擎盖下工作的?非常感谢任何见解,谢谢。

只是为了补充之前的说法,这个练习要求我实施我自己的Array.prototype.map版本。

Array.prototype.map = function(callback) {
  let arr = [];
  for(let i = 0; i < this.length; i++){
    arr.push(callback(this[i], i , this))
  }

  return arr;
}

let  ar = new Array()
javascript
1个回答
5
投票

map函数将在Array实例上调用,因此在以下代码行中:

for(let i = 0; i < this.length; i++){
    arr.push(callback(this[i], i , this))
}

是根据传递给Array.prototype.map方法的回调函数的签名:

callback生成新数组元素的函数,带有三个参数:

currentValue数组中正在处理的当前元素。

index可选数组中正在处理的当前元素的索引。

array可选调用数组映射。

因此,要在您的代码段中分解callback函数中的三个参数:

this[i]转换为map回调的第一个参数,即currentValue。正如您所理解的那样,this是调用map的数组实例。所以this[i]将引用数组的第i个索引中的值

i是指数或当前指数。这是发送到callback的for循环的迭代的第i个索引。

this是对调用map的数组本身的引用。

const arr = [1, 2, 3];
const callback = function(currentElement, index, array){
  console.log(`The current element ${currentElement}`);
  console.log(`The current index ${index}`);
  console.log(`The array instance ${array}`);
  return currentElement * 2; //multiplies each element with 2, this is the mapping operation
}
const mappedArray = arr.map(callback);
console.log(`The mapped array ${mappedArray}`);
© www.soinside.com 2019 - 2024. All rights reserved.