Closure in Javascript with multiple brackets

前端 未结 5 603
梦谈多话
梦谈多话 2021-02-01 21:00

Could any one explain how this function alert, when more no of brackets of parameters are passed. I could not able to understand it clearly.

function sum(a) {

          


        
5条回答
  •  长情又很酷
    2021-02-01 21:32

    It doesn't work as intended in all of the cases... The problem is that .toString is expected to return a string, so string methods in provided implementation, would not work, e. g. sum(2)(3).split() will cause an error.

    Although we might assume sum() result will always be expected to be a number, it might not be true in some cases and might be hard to debug, e. g. I noticed the issue when I was testing code initially written with .toString only on jsbin.com (it does split on console.log argument internally, overriding it).

    Instead, .toString should look like return String(result);. Good thing that .toString (when there's no .valueOf or modern Symbol.toPrimitive) will handle primitives conversion, so code expecting a Number will work as well. The possible issue here might be "double" conversion caused by this.

    Better solution might be to use either pair of .toString and .valueOf or just a single Symbol.toPrimitive if you're only targeting modern browsers.

    Example using Symbol.toPrimitive:

    function sum(a) {
      let result = a;
    
      function f(b) {
        result += b;
    
        return f;
      }
    
      f[Symbol.toPrimitive] = hint => hint === 'string' ? String(result) : result;
    
      return f;
    }
    

    Example using .toString and .valueOf pair.

    function sum(a) {
      var result = a;
    
      function f(b) {
        result += b;
    
        return f;
      }
    
      // avoiding double conversion which will happen in case of .toString
      f.valueOf = function() { return result; };
      f.toString = function() { return String(result); };
    
      return f;
    }
    

提交回复
热议问题