2021年4月23日星期五

javascript calling a function added as property to another function throws error

I have added a function as a property of another function as below:

function computeSum(a,...b) {      let arrSum = 0;      computeSum.counter++;      for(let num of b)          arrSum += num;      let result = a+arrSum;       return computeSum.constructSumStr(result);  }    let formSumStr = function(sum) {      return "Sum is " + sum;  };  computeSum.constructSumStr = formSumStr;    console.log(computeSum(3, 5, 6));

Now, when I call computeSum, I get the following error:

TypeError: computeSum.constructSumStr is not a function      at computeSum (C:\Rakesh\work\js-work\funcdemo.js:7:23)      at Object.<anonymous> (C:\Rakesh\work\js-work\funcdemo.js:15:23)      at Module._compile (internal/modules/cjs/loader.js:1063:30)      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)      at Module.load (internal/modules/cjs/loader.js:928:32)      at Function.Module._load (internal/modules/cjs/loader.js:769:14)      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)      at internal/main/run_main_module.js:17:47  

Whereas accessing the other property 'counter' inside computeSum() works fine. Why am I getting this error when I call the function property and how can I fix it?

https://stackoverflow.com/questions/67239484/javascript-calling-a-function-added-as-property-to-another-function-throws-error April 24, 2021 at 01:04PM

没有评论:

发表评论