jashkenas / coffeescript

Unfancy JavaScript
https://coffeescript.org/
MIT License
16.52k stars 1.98k forks source link

Global base class? #1040

Closed Xavura closed 13 years ago

Xavura commented 13 years ago

I've been playing around with CoffeeScript lately and one idea I had was a base class which all other classes would inherit from.

As an example, we could have a method that would return a bound method. There's not much difference between foo.method 'bar' and foo.bar.bind foo but still... it's just a (bad) example.

The problem is, other than explicitly extending some class for every single class created (i.e. class My326thClass extends BaseClass ...), I can't find a way to do it (without utilising major hacks).

super assumes it is within a class definition which is a pain... also __extends is a "reserved word", I found a way around it but it's all very hacky.

The easy solution of course would be to just make all classes always extend from some base class but that (c/w)ould cause lots of problems (performance, interoperability, ...) and is just a bad™ idea.

Thoughts?

erisdev commented 13 years ago

If you need a global base class for your own objects, probably you should just manually inherit from it yourself. CoffeeScript is, as I understand it, JavaScript with a new syntax—not a library adding extensive metaprogramming and other capabilities.

It's worth noting that when you write Objective-C for Apple or OPENSTEP compliant platforms, you have to explicitly inherit from NSObject to get all the goodies that it provides, including reference counting—so this is not without precedence. Objective-C's base Object class is practically useless unless you want to reimplement everything. :)

Plus, since this is intended to be totally compatible with any JavaScript you might want to mix in, adding our own magical mystical base class could make CoffeeScript less attractive for people who want to write libraries that are usable from JavaScript too.

TrevorBurnham commented 13 years ago

Exactly. CoffeeScript's classes are supposed to be lightweight, and that wouldn't be possible if they all extended a feature-rich base class.

Plus, which features should this base class have, exactly? Different projects might demand different features. Writing class My326thClass extends BaseClass for each class in your project isn't such a bad idea, if BaseClass adds functionality tailored to your project.

Another practical consideration is that you can extend a "class" written in JavaScript (such as those in Backbone.js) from CoffeeScript. But those classes wouldn't inherit from the CoffeeScript base class, if there were one; so would that CoffeeScript class have the CoffeeScript base class methods? If it did, you'd have some messy multiple inheritance issues.