Open giscafer opened 6 years ago
Hi, just stop by for studying purpose. Have a small question here:
in createMathOperation.js we got this function:
function createMathOperation(operator, defaultValue) {
return (value, other) => {
I'm very confused about where the variables 'value' and 'other' come from..... I know it consumes the parameters from add function. But how does it work (how the function createMathOperation capture those arguments from add function and then assign them to 'value' and 'other')?
I have been bothered by this whole day and did some research but still couldn't figure out... I don't even know which key word should I search. Could you kindly plz give me some clues or provide me some links? I really appreciate for that....
(use english here just because it is the only language in my computer so I hope u don't mind it)
@gislu
in js,function can as a argument, and also can be a return value in another function.
here is an arcticle: https://www.sitepoint.com/currying-in-functional-javascript/
suggest you to learning more about js function
Yeah that's exactly what I'm looking for, thx! 😆 🥂
lodash源码分析之add方法
add方法依赖的模块方法有
baseGetTag、getTag、isSymbol、baseToNumber、baseToString、createMathOperation
ES6 新增内置对象的
Symbol.toStringTag
属性值如下。JSON[Symbol.toStringTag]
:'JSON'Math[Symbol.toStringTag]
:'Math'Module 对象M[Symbol.toStringTag]
:'Module'ArrayBuffer.prototype[Symbol.toStringTag]
:'ArrayBuffer'DataView.prototype[Symbol.toStringTag]
:'DataView'Map.prototype[Symbol.toStringTag]
:'Map'Promise.prototype[Symbol.toStringTag]
:'Promise'Set.prototype[Symbol.toStringTag]
:'Set'%TypedArray%.prototype[Symbol.toStringTag]
:'Uint8Array'等WeakMap.prototype[Symbol.toStringTag]
:'WeakMap'WeakSet.prototype[Symbol.toStringTag]
:'WeakSet'%MapIteratorPrototype%[Symbol.toStringTag]
:'Map Iterator'%SetIteratorPrototype%[Symbol.toStringTag]
:'Set Iterator'%StringIteratorPrototype%[Symbol.toStringTag]
:'String Iterator'Symbol.prototype[Symbol.toStringTag]
:'Symbol'Generator.prototype[Symbol.toStringTag]
:'Generator'GeneratorFunction.prototype[Symbol.toStringTag]
:'GeneratorFunction'./.internal/baseGetTag.js
./.internal/getTag.js
主要是功能还是由baseGetTag实现判断,只是该模块对一些对象做了特殊判断处理,修补特殊环境的问题
./isSymbol.js
isSymbol 方法用来判断是否为Symbol对象
./.internal/baseToNumber.js
./.internal/baseToString.js
./.internal/createMathOperation.js
最终到
_.add
方法了,该方法里调用createMathOperation
函数创建一个加法回调,所有上边中间的模块都是对方法参数的类型判断,兼容各种类型情况,使得程序按照js
数学运算计算出结果并无异常。简单展示几种类型测试结果
add.test.js
源码+测试代码见:https://github.com/giscafer/lodash-sourcecode-study 前端学堂:felearn.com