Home >Web Front-end >JS Tutorial >Thoughts after reading 'JavaScript Functional Programming'_javascript skills
This article records some of the things I have understood while learning functional expressions, to deepen my memory and organize and record them for later review.
I made up my mind when I saw the book "JavaScript Functional Programming" on pre-sale recently. The main purpose is that I still don’t understand what functional programming is. In the process of my own learning, I have always heard people around me talking about process-oriented programming and object-oriented programming, but there are very few functional programming. In order not to fall behind other students, I wanted to share and record the knowledge I gained from reading by writing notes.
js and functional programming
The book uses a simple sentence to answer what functional programming is:
Functional programming uses functions to convert values into abstract units, which are then used to build software systems.
I think there must be students who read this sentence and still don’t know much about what functional programming is and why we should use functional programming. Many of the following examples use Underscore.
Use functions as abstract units
Abstract methods refer to functions that hide details. Take an example from the book, a function that detects the output age value (mainly reports on errors and warnings):
function parseAge(age) { if (!_.isString(age)) throw new Error("Expecting a string"); var a; console.log("Attempting to parse an age"); a = parseInt(age, 10); if (_.isNaN(a)) { console.log(["Could not parse age: "].join()); a = 0; } return a; }
The above function determines whether we have entered an age, and it must be in the form of a string. The next step is to run this function:
parseAge("42"); //=> 42 parseAge(42); //=> Error:Expecting a string parseAge("hhhh"); //=> 0
The above parseAge function works fine without any problems. If we want to change the way output error=information and warnings are presented, then we need to change the corresponding lines of code, as well as the output mode elsewhere. The method given in the book is achieved by abstracting them into different functions:
function fail(thing) { throw new Error(thing); } function warn(thing) { console.log(["WARNING:", thing].join('')); } function note(thing) { console.log(["NOTE:", thing].join('')); }
Then use the above function to reconstruct the parseAge function.
funciton parseAge(age) { if (!_.isString(age)) fail("Expecting a string"); var a; note("Attempting to parse an age"); a = parseInt(age, 10); if (_.isNaN(a)) { warn(["Could not parse age:", age].join("")); a = 0; } return a; }
Put the code that reports errors into different functions, and the refactored parseAge has not changed much from the previous one. But the difference is that now the idea of reporting errors, messages, and warnings has been abstracted. The reporting of errors, messages, and warnings has also been completely revamped.
What this does is, since the behavior is contained in a single function, the function can be replaced by a new function that provides similar behavior, or directly replaced by completely different behavior.
Encapsulation and Concealment
This title is easy to understand, here is an example. We often use iife to avoid global pollution. This is a good example of encapsulation and concealment. By using iife to hide some variables and methods you write, the purpose is not to pollute the global environment. This also uses closures to hide data.
Because closure is also a function. And it has a lot to do with learning functional programming now. But don’t forget the object-oriented encapsulation you learned before. After all, you can’t say who is better between the two. But it’s not a bad thing if you master them all. As the old saying goes: look at demand.
Use function as the unit of behavior
Hiding data and behavior (usually inconvenient for quick modification) is just a way of talking about functions as abstract units. Another approach is to provide a simple way to store and transfer basic behaviors to offline discrete units.
A small chestnut in the book, using js syntax to index a value in an array:
var arr = ['a', 'b', 'c']; arr[1] //=> b
Although indexing a value in the array above is simple, there is no way to get this behavior and use him/her as needed without putting it in a function. Write a simple function nth to index a value in the array:
function nth(a, index) { return a[index]; }
Then run:
nth(arr, 1); //=> b
The operation is successful, but if an empty object is passed in, an error will be reported. Therefore, if we want to implement function abstraction around nth, we might design the following statement: nth returns a valid function stored in a data type that allows index access. The key to this statement is the concept of the type of index data. Maybe a function is needed to determine the type:
function isIndexed(data) { return _.isArray(data) || _.isString(data); }
Then continue to improve the nth function. The isIndexed function is an abstraction that provides an abstraction for determining whether a certain data is a string or an array.
function nth(a, index) { if (!_.isNumber(index)) fail("Expected a number as the index"); if (!isIndexed(a)) fail("Not supported on non-indexed type"); if ((index < 0) || (index > a.length - 1)) fail("Index value is out of bounds"); return a[index]; }
In the same way as constructing nth function abstraction by extracting objects from index, you can also construct a second abstraction in the same way:
function second(a) { return nth(a, 1); }
函数second允许在一个不同但相关的情况下,正确的使用nth函数:
second(arr); //=> b
通过上面的栗子,就知道。我们可以把每一步都抽象成一个函数,把每一个参数都抽象出来。虽然这样写感觉定义了许多函数。不过这样更加容易理解每一项的功能和流程。
数据抽象
JavaScript 的对象原型模型是一个丰富且基础的数据方案。
因为js没有类的原因,就有了许多模拟类的方法,且在ES6上也出现了class关键字。尽管类有许多长处,但很多的时候js应用程序的数据需求币类中的简单的要多。
基于类的对象系统的一个有理的论据是实现用户界面的历史使用。
js中的对象和数组已经能够满足我们对数据的操作了,且Underscore也是重点也是如何处理数组和对象。
实施和使用的简易性是使用js的核心数据结构进行数据建模的目的。这并不是说面向对象或者基于类的方法就完全没有用。处理集合为中心的函数式方式更加适合处理与人有关的数据,而面向对象的方法最适合模拟人。
js函数式初试
在开始函数式编程前,需要先定义两个常用且有用的函数:
function existy(x) { return x != null } function truthy(x) { return (x !== false) && existy(x); }
existy函数旨在定义事物之前的存在。js中就有两个值可以表示不存在:null和undefined。
truthy函数用来判断一个对象是否应该认为是true的同义词。
我们可以在很多地方使用到这两个函数,其实函数式理念来自于它们的使用。有些同学可能已经熟悉了许多js实现中的map forEach等方法。且Underscroe也提供了许多类似的方法,这也许就是选择Underscroe来辅助学习函数式编程的原因。
简单说下就是:
一个对”存在“的抽象函数的定义。
一个建立在存在函数之上的,对”真“的抽象函数定义。
通过其他函数来使用上面的两个函数,以实现更多的行为。
加速
大概了解了函数式编程之后。你可能会想这函数式编程不是很慢吗?比如前面获取数组索引,有必要定义一个函数来专门获取吗?直接用arr[index]绝对比那些函数来的快。
var arr = [1, 2, 3, 4, 5]; // 最快 for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } // 较慢 _.each(arr, function (val, index) { console.log(index); });
但是我们在写代码的时候可能不会考虑的那么深,也许使用函数的确比原生要慢一些。但是大多数情况下也不会去在乎那么点时间,且现在有强大的v8引擎,大部分情况下的他都能很高效的编译和执行我们的js代码。所以我们没有必要在还没有写出正确的代码前考虑运算速度。
如果是我来选择的话,可能会更加关注与代码的风格。那种写法写的舒服看的舒服就使用哪一种,当然也是要保证基本的运算速度下,以不至于慢的离谱。看的舒服的代码比跑的快的代码可能更加有成就感。
总结
看完了第一章也是可以小结一下js的函数式编程。下面引用书上的总结:
确定抽象,并为其构建函数。
利用已有的函数来构建更加复杂的抽象。
通过将现有的函数传给其他的函数来构建更加复杂的抽象。
单是构建抽象还是不够的,如果能够把强大的数据抽象结合来实现函数式编程效果会更加好。
后面的章节读后感会慢慢的分享给大家,敬请关注。