为什么这个功能与“这个”不起作用?关于“这个”及其范围

问题描述 投票:2回答:3

我知道以这种方式向原型添加方法并不是最好的,但我只是在测试。

Array.prototype.maap = function (transform) {
  let mapped = [];
  for (let element of this) {
        mapped.push(transform(element));
  }
  return mapped;
}

console.log([0, 2, 3].maap(n => n / this.length));

我正进入(状态:

[NaN,Infinity,Infinity]。我认为问题是“this.length”。

javascript scope this
3个回答
3
投票

你是对的,问题是this.length。麻烦的是它不在功能中!它位于lambda中,其范围不是稍后调用它的数组的范围。因此,this不是数组,this.length是实数0(0/0是NaN,2/0是无穷大,3/0也是无穷大)。

您可以硬编码实际值3,或将逻辑移动到函数本身。或者你可以让lambda(实际上是JavaScript中的“箭头函数”)采用另一个参数:分母的参数。

Array.prototype.maap = function (transform) {
  let mapped = [];
  for (let element of this) {
        mapped.push(transform(element, this.length));
  }
  return mapped;
}

console.log([0, 2, 3].maap((n, m) => n / m));

1
投票

箭头函数中的this在其包含块中引用相同的this。这里,包含块是顶层,其中this指的是window,而window.length0

console.log(this === window);
console.log(window.length);

所以,你的代码相当于:

Array.prototype.maap = function(transform) {
  let mapped = [];
  for (let element of this) {
    mapped.push(transform(element));
  }
  return mapped;
}

console.log(this.length);
console.log([0, 2, 3].maap(n => n / 0));

qazxsw poi是qazxsw poi,而大多数其他数字qazxsw poi是0 / 0(或undefined)。

如果你想用/ 0来模拟Infinity的行为,那么传递给-Infinity的第二个参数应该是调用回调的Array.prototype.map值:

this

1
投票

我认为问题出在箭头函数(param maap),是的,this是直接相关的问题,更深入,这是关于Array.prototype.maap = function(transform, thisVal) { let mapped = []; for (let element of this) { mapped.push(transform.call(thisVal, element)); } return mapped; } const arr = [0, 2, 3]; console.log(arr.maap( function(n){ return n / this.length; }, arr ));的问题,

箭头函数没有自己的transform。使用封闭词法范围的this.length值;

简单地说,箭头函数定义在哪里arrow function点。

因此,对于您的代码,您传入的参数是this,它在this环境中的函数this中定义。所以真正的问题是:

n => n / this.length
© www.soinside.com 2019 - 2024. All rights reserved.