JavaScript OOP in NodeJS: how?

I'm used to classic OOP, like in Java.

What are the best practices for OOP in JavaScript using NodeJS?

Is each class a file with module.export ?

How to create classes?

 this.Class = function() { //constructor? var privateField = "" this.publicField = "" var privateMethod = function() {} this.publicMethod = function() {} } 

against. (I'm not even sure this is correct)

 this.Class = { privateField: "" , privateMethod: function() {} , return { publicField: "" publicMethod: function() {} } } 

against.

 this.Class = function() {} this.Class.prototype.method = function(){} ... 

How does inheritance work?

Are there specific modules for implementing OOP in NodeJS?

I find thousands of different ways to create things that resemble OOP .. but I don’t know what is the most used / practical / clean way.

Bonus question : what is the proposed "OOP style" for use with MongooseJS? (can a MongooseJS document be considered as a class and model used as an instance?)

EDIT

here is an example in JsFiddle , please provide feedback.

 //http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/ function inheritPrototype(childObject, parentObject) { var copyOfParent = Object.create(parentObject.prototype) copyOfParent.constructor = childObject childObject.prototype = copyOfParent } //example function Canvas (id) { this.id = id this.shapes = {} //instead of array? console.log("Canvas constructor called "+id) } Canvas.prototype = { constructor: Canvas , getId: function() { return this.id } , getShape: function(shapeId) { return this.shapes[shapeId] } , getShapes: function() { return this.shapes } , addShape: function (shape) { this.shapes[shape.getId()] = shape } , removeShape: function (shapeId) { var shape = this.shapes[shapeId] if (shape) delete this.shapes[shapeId] return shape } } function Shape(id) { this.id = id this.size = { width: 0, height: 0 } console.log("Shape constructor called "+id) } Shape.prototype = { constructor: Shape , getId: function() { return this.id } , getSize: function() { return this.size } , setSize: function (size) { this.size = size } } //inheritance function Square(id, otherSuff) { Shape.call(this, id) //same as Shape.prototype.constructor.apply( this, arguments ); ? this.stuff = otherSuff console.log("Square constructor called "+id) } inheritPrototype(Square, Shape) Square.prototype.getSize = function() { //override return this.size.width } function ComplexShape(id) { Shape.call(this, id) this.frame = null console.log("ComplexShape constructor called "+id) } inheritPrototype(ComplexShape, Shape) ComplexShape.prototype.getFrame = function() { return this.frame } ComplexShape.prototype.setFrame = function(frame) { this.frame = frame } function Frame(id) { this.id = id this.length = 0 } Frame.prototype = { constructor: Frame , getId: function() { return this.id } , getLength: function() { return this.length } , setLength: function (length) { this.length = length } } /////run var aCanvas = new Canvas("c1") var anotherCanvas = new Canvas("c2") console.log("aCanvas: "+ aCanvas.getId()) var aSquare = new Square("s1", {}) aSquare.setSize({ width: 100, height: 100}) console.log("square overridden size: "+aSquare.getSize()) var aComplexShape = new ComplexShape("supercomplex") var aFrame = new Frame("f1") aComplexShape.setFrame(aFrame) console.log(aComplexShape.getFrame()) aCanvas.addShape(aSquare) aCanvas.addShape(aComplexShape) console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length) anotherCanvas.addShape(aCanvas.removeShape("supercomplex")) console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length) console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length) console.log(aSquare instanceof Shape) console.log(aComplexShape instanceof Shape) 
+79
javascript inheritance oop mongoose
Aug 12 '13 at 13:20
source share
5 answers

This is an example that works out of the box. If you want to hack less, you should use the inheritance library or one.

Well in the animal.js file you would write:

 var method = Animal.prototype; function Animal(age) { this._age = age; } method.getAge = function() { return this._age; }; module.exports = Animal; 

To use it in another file:

 var Animal = require("./animal.js"); var john = new Animal(3); 

If you need a "subclass", then inside mouse.js:

 var _super = require("./animal.js").prototype, method = Mouse.prototype = Object.create( _super ); method.constructor = Mouse; function Mouse() { _super.constructor.apply( this, arguments ); } //Pointless override to show super calls //note that for performance (eg inlining the below is impossible) //you should do //method.$getAge = _super.getAge; //and then use this.$getAge() instead of super() method.getAge = function() { return _super.getAge.call(this); }; module.exports = Mouse; 

You may also consider the “Borrow method” instead of vertical inheritance. You do not need to inherit from a "class" in order to use its method for your class. For example:

  var method = List.prototype; function List() { } method.add = Array.prototype.push; ... var a = new List(); a.add(3); console.log(a[0]) //3; 
+95
Aug 12 '13 at 13:26
source share

The Node.js community ensures that new features from the ECMA-262 JavaScript specification are introduced to Node.js developers in a timely manner.

You can take a look at the JavaScript classes . MDN reference to JS classes ECMAScript 6 introduces JavaScript classes, this method provides an easier way to model OOP concepts in Javascript.

Note : JS classes will only work in strict mode .

Below is some class skeleton inheritance written in Node.js (using Node.js Version v5.0.0 )

Class declarations:

 'use strict'; class Animal{ constructor(name){ this.name = name ; } print(){ console.log('Name is :'+ this.name); } } var a1 = new Animal('Dog'); 

Inheritance:

 'use strict'; class Base{ constructor(){ } // methods definitions go here } class Child extends Base{ // methods definitions go here print(){ } } var childObj = new Child(); 
+30
Jan 18 '16 at 3:57
source share

I suggest using the helper inherits that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on a linked page.

+14
Aug 12 '13 at 13:30
source share

This is the best object oriented JavaScript video on the web:

Ultimate Object Oriented JavaScript Guide

Watch from start to finish!

Basically, Javascript is a Prototype-based language that differs from the Java, C ++, C # classes and other popular friends. The video explains the basic concepts much better than any answer here.

With ES6 (released in 2015), we got the keyword “class”, which allows us to use Javascript “classes”, as is the case with Java, C ++, C #, Swift, etc.

Screenshot from a video showing how to write and instantiate a Javascript class / subclass: enter image description here

+4
Mar 01 '17 at 4:20
source share

In the Javascript community, many people argue that OOP should not be used because the prototype model does not allow the implementation of a rigorous and reliable OOP from the very beginning. However, I do not think that OOP is a matter of language, but rather a matter of architecture.

If you want to use real strong OOP in Javascript / Node, you can take a look at Danf 's full-screen open-source framework . It provides all the necessary functions for a strong OOP code (classes, interfaces, inheritance, dependency injection, ...). It also allows you to use the same classes on the server side (node) and on the client side (browser). In addition, you can code your own danf modules and share them with anyone thanks to Npm.

+3
Nov 25 '14 at 16:59
source share



All Articles