How to implement inheritance in node.js modules?

后端 未结 3 1641
旧时难觅i
旧时难觅i 2021-01-31 09:00

I am in process of writing nodejs app. It is based on expressjs. I am confused on doing inheritance in nodejs modules. What i am trying to do is create a model base class, let\'

相关标签:
3条回答
  • 2021-01-31 09:24

    in base_model:

    function BaseModel() { /* ... */ }
    
    BaseModel.prototype.fromID = function () { /* ... */ };
    
    module.exports = BaseModel;
    

    in user_model:

    var BaseModel = require('relative/or/absolute/path/to/base_model');
    
    function UserModel() {
        UserModel.super_.apply(this, arguments);
    }
    
    UserModel.super_ = BaseModel;
    
    UserModel.prototype = Object.create(BaseModel.prototype, {
        constructor: {
            value: UserModel,
            enumerable: false
        }
    });
    
    UserModel.prototype.yourFunction = function () { /* ... */ };
    
    module.exports = UserModel;
    

    Instead of using Object.create() directly, you can also use util.inherits, so your user_model becomes:

    var BaseModel = require('relative/or/absolute/path/to/base_model'),
        util = require('util');
    
    function UserModel() {
        BaseModel.apply(this, arguments);
    }
    
    util.inherits(UserModel, BaseModel);
    
    UserModel.prototype.yourFunction = function () { /* ... */ };
    
    module.exports = UserModel;
    
    0 讨论(0)
  • 2021-01-31 09:30

    With ES6 the usage of util.inherits() is discouraged in favor of ES6 class and extends

    const EventEmitter = require('events');
    
    class MyStream extends EventEmitter {
      constructor() {
        super();
      }
      write(data) {
        this.emit('data', data);
      }
    }
    
    const stream = new MyStream();
    
    stream.on('data', (data) => {
      console.log(`Received data: "${data}"`);
    });
    stream.write('With ES6');
    
    0 讨论(0)
  • 2021-01-31 09:31

    Using utility.inherits can also help you decouple the child from the parent.

    Instead of calling the parent explicitly, you can use super_ to call the parent.

    var BaseModel = require('relative/or/absolute/path/to/base_model'),
    util = require('util');
    
    function UserModel() {
       this.super_.apply(this, arguments);
    }
    
    util.inherits(UserModel, BaseModel);
    

    utility.inherits source:

    var inherits = function (ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false
            }
        });
    };
    
    0 讨论(0)
提交回复
热议问题