Javascript toString trick in adding function. How it works?

Can someone explain to me how the toString trick works in the following example. The function adds all the arguments passed for each call, so it add(1)(2)(3);is 6.

jsFiddle

function add(a) {
  var sum = a;
    return function self(a) {
      sum += a;
      self.toString = function () {
          return sum;
      }
      return self;
  }
}

console.log(add(1)(2)(3));
+4
source share
3 answers

Since a function is a chain function, you need to return a function that needs to be bound, and then returns itself.

However, you also need a meaningful way to get its result.

jQuery, , .get(), . , .toString() " - , , ".

+3

, . self sum. console.log toString.

,

var a = add(1); //a is a self
var b = a(2); //b is the same self (b === a)
var c = b(3); //c is a same self (c === a && c === b)
console.log(c); // calls c.toString()

add, , self.

+1

add sum , :

  • , sum .

  • , sum.

, add(1) , sum 1.

The value add(1)(2)is a function where sumis 3.

The value add(1)(2)(3)is a function where sumis 6.

The call console.logwill receive the string value of the function, which is equal to sum.

You can also write basically the same code as this one, which can be a bit simpler:

function add(a) {
    var sum = a;
    function self(a) {
        sum += a;
        return self;
    }
    self.toString = function () {
        return sum;
    };
    return self;
}

console.log(add(1)(2)(3));

(The difference is that it is toStringbound by the function add, and not every time you call the return function. The edges of the edges are what console.log(add(1))show 1instead self(a).)

+1
source

Source: https://habr.com/ru/post/1544189/


All Articles