Javascript callback design: is it OK to have side effects?

时间:2015-05-08 09:54:04

标签: javascript callback

Consider this javascript function:

-sm-

Assuming that given code works correctly, let's take a look at it's design. As you can notice, #include <iostream> using namespace std; void swap(int a,int b){ int t; t=a; a=b; b=t; } void main(){ int a[]={1,2,3,4}; for (int i=1; i<3; i++) for (int j=3; j>i;j--) if(a[j]<a[j-1]) swap(a[j],a[j-1]); cout << a[0] <<a[1]<<a[2]<<a[3]; } is passed a callback function. Meanwhile, object function(){ var someArr = [...]; var someObj = {...}; someArr.forEach(function(item){ if (matchItem(item)){ someObj.callMethod(item.someProp); } }); } belongs to the scope of that callback. So from inside the callback function we can manipulate someArr.forEach.

I.e., in this case the callback produces side effects.

We could also bind someObj to someObj object of the callback:

someObj

Again, we are producing some side effects here, though in more explicit manner. In general, this approach can not be considered functional, because it violates the no-side-effects principle.

How should we design code in such situations? Which way is more robust? What are the best practices?

Thank you!

0 个答案:

没有答案