Why do javascript constructors use side effects?

I use something completely similar to the design pattern of custom objects in my code as usual.

But JSLint frowns with constructs like this:

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

Since the object is discarded immediately after creation, it is not used anywhere. We can trick JSLint into ignoring it by assigning it to a variable, but this does not change the fact that JSLint (and I guess many JavaScript enthusiasts) does not encourage the template.

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

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

  • You have one configuration function, so it should be simplified if, for example, you manage the list of MyClass instances for access later. (Clicking an object on an array is a side effect, you will need to do this after the constructor returns to be “good practice” = harder to maintain.)
  • It has its own prototype, so “class property”: Firebug reports this as an instance of MyClass, not just Object. (This, in my opinion, makes it superior to other design patterns.)
+8
javascript constructor coding-style
source share
1 answer

In his book Clean Code, Robert Martin says

Side effects are a lie. Your function promises to do one thing, but it also does other hidden things ... they are insidious and destructive violations that often lead to strange temporary connections and order dependencies.

What you described in your comment on arrays sounds like a "weird temporary connection."

+8
source share

All Articles