Skip to content

Instantly share code, notes, and snippets.

@0bie
Last active July 22, 2016 18:00
Show Gist options
  • Save 0bie/d4164cb80bbb37cc90c6700e4b7eaf18 to your computer and use it in GitHub Desktop.
Save 0bie/d4164cb80bbb37cc90c6700e4b7eaf18 to your computer and use it in GitHub Desktop.
Class/Protoype in ES5

Boilerplate structure for working w/ classes in ES5

function Module(variable1, variable2) {
    this.variable1 = variable1;
    this.variable2 = variable2;
}
Module.prototype = {
   constructor: Module, // specifies the constructor for new instances of the Module class
   currentScope: function() {console.log(this);},
   multiply: function(x, y) {
                if(arguments.length <= 1) {
                    throw new Error("multiply method requires 2 numeric values");
                } else {
                    console.log(x * y);
                }
   },
   add: function(x, y) {
            if(arguments.length <= 1) {
              throw new Error("add method requires 2 numeric values");
            } else {
              console.log(x + y);
            }
    }
};
var n = new Module();
n instanceof Module; // true
var n = new Module("hello", "world"); 
console.log(n); // Module {variable1: "hello", variable2: "world"}
n.multiply(4, 4); // 16
n.add(5, 5); // 10
n.currentScope(); // Module {variable1: "hello", variable2: "world"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment