Friday, September 1, 2017

Object Oriented Programming in JavaScript

Although I'm familiar with Object Oriented Programming (OOP) as I has been using Java for a long time, I've never tried to use it in JavaScript. When I researched OOP in JavaScript, I found it a little complicated because there exist a few ways to implemnt. In this article, I sorted out and simplified them.
  • Use function as class cannot be used in JavaScript before ES5.
var ES5Class = (function() {

    // constructor
    var ES5Class = function(member) {
        // Cope with the following usage which doesn't use new operator.
        // var instance = ES5Class();
        if(!(this instanceof ES5Class)) {
            return new ES5Class(member);
        }

        // members
        // Conventionally prefix an under score to the name of private variables.
        // (Although it can be accessed from outside the class.)
        this._member = member;
    };

    // Declare a method with prototype.
    // Methods can be declared in following way, but it's not efficient
    // because functions will be created every time an instance is generated.
    //   this.printMethod = function... 
    var p = ES5Class.prototype;
    
    // methods
    p.printMember = function () {
        console.log(this._member);
    }

    return ES5Class;
})();

module.exports = ES5Class;
  • With JavaScript later than ES6, class syntax can be used to declare classes.
class ES6Class {

    // constructor
    constructor(member) {
        // memners
        // Conventionally prefix an under score to the name of private variables.
        // (Although it can be accessed from outside the class.)
        this._member = member;
    }

    printMember() {
        console.log(this._member);
    }
}

module.exports = ES6Class
  • class syntax can also define static methods but cannot define static members.
// As there is no way to declare static members in class syntax,
// define global-scope variables instead.
var _member = 0;

class ES6StaticClass {

    // static methods
    static printMember() {
        _member++;
        console.log(_member);
    }
}

module.exports = ES6StaticClass

No comments:

Post a Comment