Home  >  Article  >  Web Front-end  >  Basic Guide to Functional Programming in JavaScript_Basics

Basic Guide to Functional Programming in JavaScript_Basics

WBOY
WBOYOriginal
2016-05-16 15:10:031459browse

Introduction

JavaScript is a powerful, yet misunderstood programming language. Some people like to say that it is an object-oriented programming language, or that it is a functional programming language. Others like to say that it is not an object-oriented programming language, or that it is not a functional programming language. Others think that it has characteristics of both an object-oriented language and a functional language, or that it is neither object-oriented nor functional. Well, let's put those arguments aside for now.

Let us assume that we share a mission: to write programs using as many functional programming principles as possible within the scope of the JavaScript language.

First of all, we need to clear up those misconceptions about functional programming in our minds.

Functional programming that is (severely) misunderstood in the JS world

Apparently there are quite a few developers who use JavaScript in a functional paradigm all day long. I would still say that there are a larger number of JavaScript developers who don't really understand the true meaning of that pretense.

I am convinced that this situation is caused by the fact that many web development languages ​​​​used on the server side are derived from C language, and C language is obviously not a functional programming language.

There seem to be two levels of confusion. Let’s use the following example that is often used in jQuery to illustrate the first level of confusion:

$(".signup").click(function(event){
  $("#signupModal").show();
  event.preventDefault();
});

Hey, look carefully. I pass an anonymous function as a parameter, which is known in the JavaScript world as a "CallBack" function.

Does anyone really think this is functional programming? Not at all!

This example demonstrates a key feature of functional languages: functions as parameters. On the other hand, this 3-line example also goes against almost every other functional programming paradigm.

The second level of chaos is a little more subtle. After reading this, some trend-seeking JS developers are thinking secretly.

Okay, crap! But I already know everything there is to know about functional programming. I use Underscore.js on all my projects.

Underscore.js is a popular JavaScript library used everywhere. For example, I have a set of words, and I need to get a set where each element in the set is the first two letters of each word. Implementing this with Underscore.js is fairly simple:

var firstTwoLetters = function(words){
  return _.map(words,function(word){
    return _.first(word,2);
  });
};

Look! See JavaScript Wizardry. I'm using these advanced functional application functions like _.map and _.first. Is there anything else you want to say, Leland?

Although highlights and functions like _.map are very valuable pieces of the functional paradigm, the way the code is organized like the one used in this example seems... verbose and too difficult for me to understand. Do we really need to do this?

If we start thinking with a little more "functional" thinking, maybe we can change the above example to this:

// ...一点魔法
var firstTwoLetters = map(first(2));

Think about it carefully, one line of code contains the same information as the five lines of code above. words and word are just parameters/placeholders. The core of this method is to combine the map function, the first function, and the constant 2 in a more obvious way.

Is JavaScript a functional programming language?

There is no magic formula to determine whether a language is a "functional" language. Some languages ​​are clearly functional, just as other languages ​​are clearly not functional, but there are plenty of languages ​​that fall somewhere in the ambiguous middle.

So here are some commonly used and important "ingredients" of functional languages ​​(JavaScript can use bold symbols)

  • Functions are “first class citizens”
  • Functions can return functions
  • Lexically supports closures
  • Functions must be “pure”
  • Reliable Recursion
  • No mutation status

This is by no means an exclusive list, but we will at least discuss one by one the three most important features of Javascript that enable us to write programs in a functional way.

Let’s take a closer look at each one:

Functions are “first class citizens”

This one is probably the most obvious of all ingredients, and probably the most common in many modern programming languages.

Local variables in JavaScript are defined through the var keyword.

var foo = "bar";

It is very easy to define functions as local variables in JavaScript.

var add = function (a, b) { return a + b; };
var even = function (a) { return a % 2 === 0; };

These are all facts, variables: variable add and variable even establish a reference relationship with the function definition by being assigned a value. This reference relationship can be changed at any time if necessary.

// capture the old version of the function
var old_even = even; 
 
// assign variable `even` to a new, different function
even = function (a) { return a & 1 === 0; };

Of course, this is nothing special. But the important feature of being a "first-class citizen" allows us to pass a function to another function as a parameter. For example:

var binaryCall = function (f, a, b) { return f(a, b); };

这是一个函数,他接受了一个二元函数f,和两个参数a,b,然后调用这个二元函数f,该二元函数f以a、b为输入参数。

add(1,2) === binaryCall(add, 1, 2); 
// true

这样做看起来有点笨拙,但是当把接下来的函数式编程“配料”合并考虑的时候,牛叉之处就显而易见了…

函数能返回函数(换个说法“高阶函数”)

事情开始变的酷起来。尽管开始比较简单。函数最终以新的函数作为返回值。举个例子:

var applyFirst = function (f, a) { 
 return function (b) { return f(a, b); };
};

这个函数(applyFirst)接受一个二元函数作为其中一个参数,可以把第一个参数(即二元函数)看作是这个applyFirst函数的“部分操作”,然后返回一个一元(一个参数)函数,该一元函数被调用的时候返回外部函数的第一个参数(f)的二元函数f(a, b)。返回两个参数的二元函数。

让我们再谈谈一些函数,例如mult(乘法)函数:

var mult = function(a, b) { return a * b; };

依循mult(乘法)函数的逻辑,我们可以写一个新的函数double(乘方):

var double = applyFirst(mult, 2);
 
double(32); 
// 64
double(7.5); 
// 15

这就是偏函数,在FP中经常会用到。(译注:FP全名为 Functional Programming 函数式程序设计 )

我们当然可以像applyFirst那样定义函数:

var curry2 = function (f) {
 return function (a) {
  return function (b) {
   return f(a, b);
  };
 };
};

现在,我想要一个double(乘方)函数,我们换种方式做:

var double = curry2(mult)(2);

这种方式被称作“函数柯里化”。有点类似partial application(偏函数应用),但是更强大一点。

准确的说,函数式编程之所以强大,大部分因于此。简单和易理解的函数成为我们构筑软件的基础构件。当拥有高水平的组织能力、很少重用的逻辑的时候,函数能够被组合和混合在一起用来表达出更复杂的行为。

高阶函数可以得到的乐趣更多。让我们看两个例子:

1.翻转二元函数参数顺序

// flip the argument order of a function
var flip = function (f) {
 return function (a, b) { return f(b, a); };
};
 
divide(10, 5) === flip(divide)(5, 10); 
// true

2.创建一个组合了其他函数的函数

// return a function that's the composition of two functions...
// compose (f, g)(x) -> f(g(x))
var compose = function (f1, f2) {
 return function (x) {
  return f1(f2(x));
 };
};
 
// abs(x) = Sqrt(x^2)
var abs = compose(sqrt, square);
 
abs(-2); 
// 2

这个例子创建了一个实用的函数,我们可以使用它来记录下每次函数调用。

var logWrapper = function (f) {
 return function (a) {
  console.log('calling "' + f.name + '" with argument "' + a);
  return f(a);
 };
};

var app_init = function(config) { 
/* ... */
 };
 
if(DEBUG) {
 
// log the init function if in debug mode
 app_init = logWrapper(app_init);
}
 
// logs to the console if in debug mode
app_init({
 
/* ... */
});

词法闭包+作用域

我深信理解如何有效利用闭包和作用域是成为一个伟大JavaScript开发者的关键。
那么…什么是闭包?

简单的说,闭包就是内部函数一直拥有父函数作用域的访问权限,即使父函数已经返回。61bc4fd3a408f9b7fe12fc5564f7379b
可能需要个例子。

var createCounter = function () {
 var count = 0;
 return function () {
  return ++count;
 };
};
 
var counter1 = createCounter();
 
counter1(); 
// 1
counter1(); 
// 2
 
var counter2 = createCounter();
 
counter2(); 
// 1
counter1(); 
// 3

一旦createCounter函数被调用,变量count就被分配一个新的内存区域。然后,返回一个函数,这个函数持有对变量count的引用,并且每次调用的时候执行count加1操作。

注意从createCounter函数的作用域之外,我们是没有办法直接操作count的值。Counter1和Counter2函数可以操作各自的count变量的副本,但是只有在这种非

常具体的方式操作count(自增1)才是被支持的。

在JavaScript,作用域的边界检查只在函数被声明的时候。逐个函数,并且仅仅逐个函数,拥有它们各自的作用域表。(注:在ECMAScript 6中不再是这样,因为let的引入)

一些进一步的例子来证明这论点:

// global scope
var scope = "global";
 
var foo = function(){
 
// inner scope 1
 var scope = "inner";
 var myscope = function(){
  
// inner scope 2
  return scope;
 };
 return myscope;
};
 
console.log(foo()()); 
// "inner"
 
console.log(scope); 
// "global"

关于作用域还有一些重要的事情需要考虑。例如,我们需要创建一个函数,接受一个数字(0-9),返回该数字相应的英文名称。

简单点,有人会这样写:

// global scope...
var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
var digit_name1 = function(n){
 return names[n];
};

但是缺点是,names定义在了全局作用域,可能会意外的被修改,这样可能致使digit_name1函数所返回的结果不正确。
那么,这样写:

var digit_name2 = function(n){
 var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
 return names[n];
};

这次把names数组定义成函数digit_name2局部变量.这个函数远离了意外风险,但是带来了性能损失,由于每次digit_name2被调用的时候,都将重新为names数组定义和分配空间。换个例子如果names是个非常大的数组,或者可能digit_name2函数在一个循环中被调用多次,这时候性能影响将非常明显。

// "An inner function enjoys that context even after the parent functions have returned."
var digit_name3 = (function(){
 var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
 return function(n){
  return names[n];
 };
})();

这时候我们面临第三个选择。这里我们实现立即调用的函数表达式,仅仅实例化names变量一次,然后返回digit_name3函数,在 IIFE (Immediately-Invoked-Function-Expression 立即执行表达式)的闭包函数持有names变量的引用。
这个方案兼具前两个的优点,回避了缺点。搞定!这是一个常用的模式用来创建一个不可被外部环境修改“private”(私有)状态。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn