我正在重新学习Javascript知识,并填补了一些空白。
对于备忘录功能,我知道为什么它将控制台记录该功能,因为memoizeSomeFunction const只是将someFunction的函数表达式作为arg传递给备忘录。我似乎无法概念化的是,传递给memoizeSomeFunction的arg如何到达函数的返回部分。有人可以详细说明吗?
const memoize = (fn) => {
console.log(fn);
return (arg) => {
console.log(arg)
}
}
const someFunction = (x = 0, y = 0) => {
return `x is {$x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction);
memoizeSomeFunction(1)
答案 0 :(得分:2)
memoize()
函数返回一个函数:
(...args) => {
console.log(...args)
}
该函数使用传播(...
)语法将其参数收集到数组中,然后在console.log()
调用中以相同的方式取消收集它们。
因此,当您调用从memoize()
返回的函数时,它仅记录传递的参数。
总结:
memoize()
函数someFunction()
; memoize()
函数返回另一个函数,该函数记录其参数(否则对someFunction()
不执行任何操作); memoize()
时记录函数源,并在每次调用时记录返回值的参数列表。如果您向该返回的函数添加了另一个调用,则会看到这些参数分别记录。答案 1 :(得分:1)
// ES5 equivalent:
const memoize_es5 = function(fn) {
// fn is closured and can be used
// function returned, when it will be called we will have call arguments as well
return function () {
console.log(fn.apply(null, arguments));
}
}
const memoize = fn => (...args) => console.log(fn(...args));
const someFunction = (x = 0, y = 0) => {
return `x is ${x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction); // function received as result of memoize call
memoizeSomeFunction(1, 15); // pass arguments to that function function
// ...args in the arguments is a rest operator
// it just capture all rest arguments into an array:
((first, ...args) => console.log(first, args))(1, 2, 3)
// ...args in a function call is spread operator
// it spreads an array into parameter list:
console.log(...['spread', 'operator'])
答案 2 :(得分:1)
固化可以帮助您更好地理解这一点。
考虑这样的功能
const currying = (x) => {
console.log(x);
return (y) => {
console.log(y);
return (z) => {
console.log(z);
}
}
}
currying(1)(2)(3);
基本上
const memoizeSomeFunction = memoize(someFunction);
memoizeSomeFunction(1, 15);
与
相同memoize(someFunction)(1, 15)
类似于
currying(1)(2)
currying = (x) => {
return (y) => {
//
}
}
,与
相同currying = (fn) => {
return (...args) => {
//
}
}
这是一篇关于curring的文章。
https://hackernoon.com/currying-in-js-d9ddc64f162e
希望这会有所帮助!