先看下下面这个函数
function createMathOperation(operator, defaultValue) {
return (value, other) => { // 这个写法很奇妙,createMathOperation直接调用了operator的参数,在看不出任何引用的情况下,它是如何做到的?
let result
if (value === undefined && other === undefined) { //如果两个参数都不存在,返回defaultValue
return defaultValue
}
if (value !== undefined) { //如果存在value,就返回value
result = value
}
if (other !== undefined) { //如果存在other
if (result === undefined) { //如果存在other,且value不存在(这里为什么不写成value === undefined?,看上去是一样的,且value更好理解),返回other
return other
}
if (typeof value == 'string' || typeof other == 'string') { //如果两个参数中有字符串
value = baseToString(value)
other = baseToString(other)
} else {
value = baseToNumber(value)
other = baseToNumber(other)
}
result = operator(value, other)
}
return result
}
}
const add = createMathOperation((augend, addend) => augend + addend, 0);
add(4,6); // --> 10
我自己猜测是operator(value, other) 是作用域链的关系能访问到了箭头函数的value与other,但最
奇妙的在于它调用的时候:
这个add(4, 6); 发生了什么?4、6作为createMathOperation(){}
的参数可以理解,怎么就被operator(){}
拿到了?
求大神指点 传道 受业 解惑啊
其实就是一个经典闭包吧。你说的operator其实就是(augend, addend) => augend + addend这个function。然后你说你的4和6不是createMathOperation拿到了,而是return出来的function拿到了