JavaScript OOP in NodeJS: how?

前端 未结 6 1857
野的像风
野的像风 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 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.

提交回复
热议问题