d5sgfq
Last Updated: February 25, 2016
·
1.352K
· mutahhir
2034643609a3d51207127b00dfacce5f

How I write Javascript classes

There are a lot of ways to write javascript classes, and I'm not here to give a technical description and how one method is better than others. I'm just sharing how I write them and why they feel aesthetically more pleasing to me.

var Klass = function() {
};

(function() {

    this.method = function method() {
    };

}).call(Klass.prototype); 

I think I started doing this by observing how the ACE source code was written. I think. I like how I don't have to keep on typing Klass.prototype. every time, and also don't have to go 'Doh!' each time I miss a comma in the Klass.prototype = {}; method.

Though the downside in this method is that you can't use the getter/setter syntax like:

Klass.prototype = {
  get value(){
      return this._value;
  },
  set value(val){
      this._value = val;
  }
};

but instead have to use this verbose method:

this.__defineGetter__("value", function(){
    return value;
});

this.__defineSetter__("value", function(val){
    value = val;
});

2 Responses
Add your response

2726
D42a7264714dee5006b9c99d2567a320

How do you do inheritance?
Also, do you use doc comments?

over 1 year ago ·
2736
2034643609a3d51207127b00dfacce5f

@dpashkevich I just posted another protip regarding how I use inheritance. Hopefully should be interesting for you.

over 1 year ago ·