David Flanagan의 "Javascript : The Definitive Guide"를 살펴 보겠습니다.Flanagan의 "JS : Definitive Guide"에 memoize 기능이 필요한 이유는 무엇입니까? length?
그가 인수로 함수를 받아들이는 고차 기능,memoize()
을 보여주고 기능의 memoized 버전 반환 단락 8.8.4에서
:이 설명에서
//Return a memoized version of f.
// It only works if arguments to f all have distinct string representations.
function memoize(f) {
var cache = {}; // Value cache stored in the closure.
return function() {
// Create a string version of the arguments to use as a cache key.
var key = arguments.length + Array.prototype.join.call(arguments,",");
if (key in cache) return cache[key];
else return cache[key] = f.apply(this, arguments);
}
}
은 "반환 함수 은 인수 배열을 문자열 "으로 변환합니다.
인수 만 필요하면 왜 인수 배열을 문자열로 변환하는 대신 arguments.length
을 Array.prototype.join.call(arguments, ",")
과 연결해야합니까? 그렇지 않으면이 두 호출이 동일한 키에 저장 될 수 있기 때문에
나중에 호출 캐시에 액세스하기 때문에 사용됩니다. 다른 수의 매개 변수를 사용하여 메서드를 호출하면 차이가 있습니다. –