Why is using side effects bad practice in JavaScript constructors?

我怕爱的太早我们不能终老 提交于 2021-02-07 05:47:26

问题


I use something quite similar to the design pattern custom objects in my code normally.

But JSLint frowns upon constructs like this:

function MyClass() { this.init(); }
new MyClass(data);

Because the object is being discarded immediately after creation - it isn't being used for anything. We can fool JSLint to ignore this by assigning it to a variable, but it doesn't change that JSLint (and I am guessing many JavaScript enthusiasts) discourages the pattern.

So why is using side effects in a JavaScript constructor seen as a bad practice?

For what it's worth, I thought this was a good practice because:

  1. You have one setup function, thus it should be easier to maintain if e.g. you are managing a list of MyClass instances for access later. (Pushing an object onto an array is a side effect, you would have to do it after the constructor returned to be "good practice" = harder to maintain.)
  2. It has its own prototype, thus a "class ownership": Firebug reports this as an instance of MyClass instead of just Object. (This, in my opinion, makes it superior to the other design patterns.)

回答1:


In his book Clean Code, Robert Martin says

Side effects are lies. Your function promises to do one thing, but it also does other hidden things...they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.

What you described in your comment regarding arrays sounds like a "strange temporal coupling".



来源:https://stackoverflow.com/questions/14694982/why-is-using-side-effects-bad-practice-in-javascript-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!