4

I've been writing coffeescript for a little while now and ran into something a bit peculiar.

Traditionally coffeescript declares all prototype methods individually like such:

MyClass.prototype.firstMethod = function(){...};
MyClass.prototype.secondMethod = function(){...};

However, MDN says a better way would be to do this:

(function() {
 this.firstMethod = function(){...};
 this.secondMethod = function(){...};
}).call(MyClass.prototype);

For the source please refer to the very end example of this page.

I was under the impression that coffeescript tries to render the best possible javascript. Is one way truly better (or possibly different) than the other or is it simply preference?

Thanks for reading!

EDIT: Seems that this question has no real answer and comes down to matter of opinion. I will leave it up for another 2 hours before deleting it. I'd like to thank everyone for their input, it helped me understand this topic better.

  • I suppose one improvement would be making it easier to add the same methods to more than one class, like `function add_methods(MyClass){the second code block here}`. – Jared Farrish Apr 24 '15 at 17:16
  • MDN doesn't say that the second is *better*, they say it is *cleaner*: "The above code can also be written in a cleaner way with the same result." – mu is too short Apr 24 '15 at 17:29
  • @muistooshort You're technically right. You're suggesting that MDN is suggesting that it comes to preference and has no other impact. Cleaner could equal better but that is subjective. I guess I want to get a general consensus if no one can offer an actual exclusive benefit to using one or the other. – user3669257 Apr 24 '15 at 17:33
  • Also note that the MDN didn't say it was better, it said it was "cleaner", which isn't quantifiable (though, "better" is the same). From my point of view it doesn't look any more or less clean. It does however give you a few other options that you wouldn't have otherwise (private variables/methods that are shared for all instances for example.) – Kevin B Apr 24 '15 at 17:35

2 Answers2

3

The coffeescript transpiler doesn't render the "best" possible javascript. It just does what the contributors to it want it to do. Also, "best" is a matter of opinion in some cases so there will differences anyway.

Transcendence
  • 2,616
  • 3
  • 21
  • 31
1

This is probably going to get closed due to being argumentative, but from my perspective the second is a nice options when dealing with (and encapsulating) scope. You see a lot of IIFE's so you're not accidentally referencing this in the default (global) scope. In an IIFE you're limiting the opportunity to collide with other module definitions.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200