JavaScript OOP in NodeJS: how?

前端 未结 6 1856
野的像风
野的像风 2021-01-29 18:31

I am used to the classical OOP as in Java.

What are the best practices to do OOP in JavaScript using NodeJS?

Each Class is a file with module.export

相关标签:
6条回答
  • 2021-01-29 18:45

    This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.

    Well in a file animal.js 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 other file:

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

    If you want a "sub class" 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 (e.g. 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;
    

    Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:

     var method = List.prototype;
     function List() {
    
     }
    
     method.add = Array.prototype.push;
    
     ...
    
     var a = new List();
     a.add(3);
     console.log(a[0]) //3;
    
    0 讨论(0)
  • 2021-01-29 18:46

    I suggest to use the inherits helper 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 the linked page.

    0 讨论(0)
  • 2021-01-29 18:51

    In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.

    If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.

    0 讨论(0)
  • 2021-01-29 18:52

    This is the best video about Object-Oriented JavaScript on the internet:

    The Definitive Guide to Object-Oriented JavaScript

    Watch from beginning to end!!

    Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.

    With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.

    Screenshot from the video showing how to write and instantiate a Javascript class/subclass:

    0 讨论(0)
  • 2021-01-29 18:55

    As Node.js community ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner.

    You can take a look at JavaScript classes. MDN link to JS classes In the ECMAScript 6 JavaScript classes are introduced, this method provide easier way to model OOP concepts in Javascript.

    Note : JS classes will work in only strict mode.

    Below is some skeleton of class,inheritance written in Node.js ( Used 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();
    
    0 讨论(0)
  • 2021-01-29 19:02

    If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

    Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

    crx_registerClass("ExampleClass", 
    { 
        "VERBOSE": 1, 
    
        "public var publicVar": 5, 
        "private var privateVar": 7, 
    
        "public virtual function publicVirtualFunction": function(x) 
        { 
            this.publicVar1 = x;
            console.log("publicVirtualFunction"); 
        }, 
    
        "private virtual function privatePureVirtualFunction": 0, 
    
        "protected virtual final function protectedVirtualFinalFunction": function() 
        { 
            console.log("protectedVirtualFinalFunction"); 
        }
    }); 
    
    crx_registerClass("ExampleSubClass", 
    { 
        VERBOSE: 1, 
        EXTENDS: "ExampleClass", 
    
        "public var publicVar": 2, 
    
        "private virtual function privatePureVirtualFunction": function(x) 
        { 
            this.PARENT.CONSTRUCT(pA);
            console.log("ExampleSubClass::privatePureVirtualFunction"); 
        } 
    }); 
    
    var gExampleSubClass = crx_new("ExampleSubClass", 4);
    
    console.log(gExampleSubClass.publicVar);
    console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
    

    The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.

    0 讨论(0)
提交回复
热议问题