Home > Web Front-end > JS Tutorial > js implements a method similar to the add(1)(2)(3) calling method_javascript skills

js implements a method similar to the add(1)(2)(3) calling method_javascript skills

WBOY
Release: 2016-05-16 16:11:18
Original
1308 people have browsed it

Copy code The code is as follows:

var add = function(a){
Return function(b){
         return function(c){
               return a b c;
        };
};
};
add(1)(2)(3); //6

That’s right! If there are four calls like add(1)(2)(3)(4), then this will definitely not apply.

This is similar to executing a function and returning the value of the function itself:

Copy code The code is as follows:

function add(x) {
var sum = x;
var tmp = function (y) {
sum = sum y;
         return tmp;
};
tmp.toString = function () {
        return sum;
};
Return tmp;
}
console.log(add(1)(2)(3)); //6
console.log(add(1)(2)(3)(4)); //10

But after the calculation is completed, the tmp function is still returned, so the calculation result cannot be obtained. The result we need is a calculated number. So what should we do? First, we must know how to print and add calculations in JavaScript. , will call the toString or valueOf function respectively, so we rewrite the toString and valueOf methods of tmp to return the value of sum;

The above is the entire content of this article, I hope you all like it.

Related labels:
js
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