Home > Web Front-end > JS Tutorial > A brief analysis of Javascript closures and function currying (graphic tutorial)

A brief analysis of Javascript closures and function currying (graphic tutorial)

亚连
Release: 2018-05-21 09:38:14
Original
1052 people have browsed it

This article mainly introduces Javascript closures and currying. It is easy to understand and friends in need can refer to it.

Closures and currying are both frequently used and relatively advanced techniques in JavaScript. All functional programming languages ​​support these two concepts. Therefore, we want to give full play to the functions in JavaScript. Programming features require an in-depth understanding of these two concepts. In fact, closure is an indispensable foundation for currying.

1. The concept of currying

In computer science, currying is to transform a function that accepts multiple parameters into a function that accepts a single parameter (the original function A function that takes the first argument) and returns a new function that accepts the remaining arguments and returns a result. This technique was named by Christopher Strachey after logician Haskell Curry, although it was invented by Moses Schnfinkel and Gottlob Frege. Intuitively, currying states that "if you fix some parameters, you will get a function that accepts the remaining parameters." So for a function yx with two variables, if y = 2 is fixed, we get a function 2x with one variable.

Currying is to pass in some parameters of the function in advance to get a simple function. But the parameters passed in beforehand are saved in the closure, so there will be some peculiar characteristics. For example:

var adder = function(num){
  return function(y){
     return num + y;
  }
}
var inc = adder(1);
var dec = adder(-1)
Copy after login

The two variables inc/dec here are actually two new functions, which can be called through brackets, such as the following example Usage in:

//inc, dec现在是两个新的函数,作用是将传入的参数值(+/-)1
print(inc(99));//100
print(dec(101));//100
print(adder(100)(2));//102
print(adder(2)(100));//102
Copy after login

2. Application of currying

According to the characteristics of currying, we You can write more interesting code. For example, in front-end development, we often encounter this situation. When the request returns from the server, we need to update some specific page elements, which is the concept of partial refresh. Using partial refresh is very simple, but the code can easily become a mess. And if we use currying, we can beautify our code to a great extent and make it easier to maintain. Let’s look at an example:

//update会返回一个函数,这个函数可以设置id属性为item的web元素的内容
function update(item){
  return function(text){
     $("p#"+item).html(text);
  }
}
//Ajax请求,当成功是调用参数callback
function refresh(url, callback){
  var params = {
     type : "echo",
     data : ""
  };
  $.ajax({
     type:"post",
     url:url,
     cache:false,
     async:true,
     dataType:"json",
     data:params,
     //当异步请求成功时调用
     success: function(data, status){
        callback(data);
     },
     //当请求出现错误时调用
     error: function(err){
        alert("error : "+err);
     }
  });
}
refresh("action.do?target=news", update("newsPanel"));
refresh("action.do?target=articles", update("articlePanel"));
refresh("action.do?target=pictures", update("picturePanel"));
其中,update函数即为柯里化的一个实例,它会返回一个函数,即:
update("newsPanel") = function(text){
  $("p#newsPanel").html(text);
}
Copy after login

Since the return value of update(“newsPanel”) is a function, the required parameter is a string. Therefore, in the refresh Ajax call, when success occurs, the data information returned by the server will be passed to the callback, so as to refresh the newsPanel panel. Other article panels articlePanel and picture panel picturePanel are refreshed in this way. In this way, The readability and maintainability of the code have been improved.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

What are the methods for php to read local json files

php Read, write and modify js Detailed explanation of the steps on file

About the difference between String() and .toString() in JS (combined with the code, it is clear at a glance)

The above is the detailed content of A brief analysis of Javascript closures and function currying (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template