JS implementation is similar to the method of the Add (1) (2) (3) Call mode

Source: Internet
Author: User

Someone in the group said to implement a method similar to the Add (1) (2) (3) invocation, the result is immediately answered:

  1. var add = function(a) {
  2. return function(b) {
  3. return function(c) {
  4. return a+b+c;
  5. };
  6. };
  7. };
  8. Add(1) (2) (3); //6

That's right! If Add (1) (2) (3) (4) Such 4 calls, then this certainly does not apply.

This is analogous to executing a function that returns the value of the function itself:
  1. function Add(x) {
  2. var sum = x;
  3. var tmp = function (y) {
  4. Sum = sum + y;
  5. return tmp;
  6. };
  7. TMP. toString = function () {
  8. return sum;
  9. };
  10. return tmp;
  11. }
  12. Console. Log(add(1) (2) (3)); //6
  13. Console. Log(add(1) (2) (3) (4)); //10

First, a number to remember each time the calculated value, so use a closure, the value of X is remembered in TMP, the first call to add (), initialize the TMP, and the x is stored in the TMP chain, and then return to TMP to ensure that the second call is the TMP function, the subsequent calculation is called TMP, Because TMP is also the return itself, it is guaranteed that the second call is also called TMP, while the parameters passed in TMP are added to the x in the chain of action and paid to sum, thus guaranteeing the calculation;

But after the completion of the calculation or return to the TMP function, so that we can not get the results of the calculation, we need the result is a calculated number then what to do, first of all to know JavaScript, print and add calculation, will call the ToString or valueof function, respectively, So we rewrite TMP's ToString and valueof methods, returning the value of sum;

Excerpt from: http://www.css88.com/archives/5147#more-5147

JS implementation is similar to the method of the Add (1) (2) (3) Call mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.