I was learning about arrays methods and there's one thing I don't quite understand, possibly related to closures.(我正在学习数组方法,有一件事我不太了解,可能与闭包有关。)
First things first though, here's the code snippet:(首先,这是代码片段:)
let range = { minNumber: 20, maxNumber: 30, isValid(number) { return number >= this.minNumber && number < this.maxNumber; } }; let numbers = [16, 23, 27, 30, 45]; let filteredNumbers = numbers.filter(range.isValid, range); console.log(filteredNumbers.length); // 2 console.log(filteredNumbers[0]); // 23 console.log(filteredNumbers[1]); // 27
From what I understand by passing second argument we bind this
to range
, otherwise simply calling: numbers.filter(range.isValid)
will make this
undefined.(从我通过传递第二个参数,我们绑定明白this
对range
,否则简单的调用: numbers.filter(range.isValid)
将使this
不确定的。)
this
either way though, as we're "calling" isValid
from range
context by using .
(但是,它不应该以任何一种方式访问this
方法,因为我们使用来从range
上下文“调用” isValid
.
) operator?(操作员?)
There is also a second approach that works:(还有另一种有效的方法:)
numbers.filter(number => range.isValid(number))
What's going on here?(这里发生了什么?)
Now it's able to pick upthis
from range
object all of a sudden?(现在,能够拿起this
从range
对象一下子?) Arrow functions have no this
iirc, so it's not that.(箭头函数没有this
iirc,所以不是。)
Thanks for all the help in advance.(感谢您提前提供的所有帮助。)
:)(:)) ask by flamasterrr translate from so