Last Updated: February 25, 2016
·
1.764K
· mutahhir

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

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

over 1 year ago ·

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

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside