gpt4 book ai didi

javascript - 这个闭包中的参数是在哪一点传递的?

转载 作者:行者123 更新时间:2023-11-30 17:31:27 25 4
gpt4 key购买 nike

取自Secrets of the JavaScript Ninja , list 5.14 将 isPrimenum 参数传递给一个 memoized 函数,我假设 num 参数是可见的在#1,而不是在#2,但实际上是相反的!

Function.prototype.memoized = function(key){
this._values = this._values || {};
return this._values[key] !== undefined ?
this._values[key] :
this._values[key] = this.apply(this, arguments);
};

Function.prototype.memoize = function() {
var fn = this; //#1
console.log(Array.prototype.slice.call(arguments)); // Prints []

return function(){ //#2
console.log(Array.prototype.slice.call(arguments)); //Prints [17]
return fn.memoized.apply(fn, arguments);
};
};

var isPrime = (function(num) {
var prime = num != 1;
for (var i = 2; i < num; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
return prime;
}).memoize();

assert(isPrime(17), "17 is prime"); //#3

num 参数(在本例中为 17)怎么可能只在 inner 闭包(#2)中可见,而不在包装 memoize 函数中可见?我不明白 memoize() 调用在什么时候将 num 参数传递到#2 中的闭包。

附言。重申并补充上述问题:为什么我在 #1 中看不到 num 参数?

谢谢。

最佳答案

因为 #2 是分配给 isPrime 的函数。然后将 17 传递给 isPrime。另一方面,您调用 .memoize (#1) 而不向其传递任何参数:

(function() { ... }).memoize()
// ^^ no arguments

I don't understand at which point the memoize() call passes the num argument to the closure in #2.

事实并非如此。 memoize 返回一个新函数,它是参数传递到的那个函数。

关于javascript - 这个闭包中的参数是在哪一点传递的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22993462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com