JavaScript OOP in NodeJS: how?

前端 未结 6 1865
野的像风
野的像风 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: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();
    

提交回复
热议问题