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"}
- In the code above we define a constructor function called
Module
. Constructor functions can be used to define classes in JS and should always be written in Pascal case - The prototype object must always be appended with
.prototype
E.gModule.prototype
. By doing this, an invocation of theModule()
constructor automatically usesModule.prototype
as the prototype of thenew
Module object - The prototype object is fundamental to the identity of a class; this is what gets checked when you test objects for membership in a class using
instanceof
E.g n instanceof Module
returnstrue
ifn
inherits fromModule.prototype
- To create a new instance of the class above (
Module
) we invoke theModule()
constructor with thenew
keyword E.gvar n = new Module
- Two objects are instances of the same class if and only if they inherit from the same prototype object
- The prototype of an object (
__proto__
) is not the same thing as the prototype property of the object. The former is used when looking up non-existent properties in the prototype chain. The latter is used for objects created using new, it will be the prototype of the newly created object. - Further reading:
- https://coderwall.com/p/j1khtg/javascript-difference-between-__proto__-and-prototype
- http://dailyjs.com/2012/05/20/js101-prototype/
- http://dailyjs.com/2012/11/26/js101-proto/
- http://dailyjs.com/2012/05/27/js101-prototype-chains/
- http://bytearcher.com/articles/understanding-prototype-property-in-javascript/