问题
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:
- 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.)
- 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