util.inherits - alternative or workaround

后端 未结 4 765
面向向阳花
面向向阳花 2021-02-05 08:46

I am a n00b in node, and find util.inherits() very useful, except for the fact that it seems to replace the entire prototype of the original object. For instance:

4条回答
  •  温柔的废话
    2021-02-05 09:20

    As of node version 5.0.0, util.inherits has been changed to support the behaviour you are looking for using the setPrototypeOf method:

    FirstBase.js

    function FirstBase(firstBaseProp){
        this.firstBaseProp = firstBaseProp;
    }
    
    FirstBase.prototype.getFirstBaseProp = function(){
        return this.firstBaseProp;
    };
    
    
    module.exports = FirstBase;
    

    SecondBase.js

    var FirstBase = require('./FirstBase.js'),
        util = require('util');
    
    function SecondBase(firstBaseProp, secondBaseProp){
        this.secondBaseProp = secondBaseProp;
        SecondBase.super_.apply(this, arguments);
    }
    
    SecondBase.prototype.getSecondBaseProp = function(){
        return this.secondBaseProp;
    };
    
    util.inherits(SecondBase, FirstBase);
    
    module.exports = SecondBase;
    

    ThirdBase.js

    var SecondBase = require('./SecondBase.js'),
        util = require('util');
    
    function ThirdBase(firstBaseProp, secondBaseProp, thirdBaseProp){
        this.thirdBaseProp = thirdBaseProp;
        ThirdBase.super_.apply(this, arguments);
    }
    
    ThirdBase.prototype.getThirdBase = function(){
        return this.thirdBaseProp;
    };
    
    util.inherits(ThirdBase, SecondBase);
    
    module.exports = ThirdBase;
    

    instance.js

    var ThirdBase = require('./ThirdBase.js');
    
    var instance = new ThirdBase('first', 'second', 'third');
    
    // With node < 5.0.0 (Object.create)
    console.log(instance.getFirstBaseProp()); // first
    console.log(instance.getSecondBaseProp()); // undefined
    console.log(instance.getThirdBase()); // undefined
    
    // With node >= 5.0.0 (Object.setPrototypeOf)
    console.log(instance.getFirstBaseProp()); // first
    console.log(instance.getSecondBaseProp()); // second
    console.log(instance.getThirdBase()); // third
    

    If you're running an older version of node that supports setPrototypeOf (0.12.x does), you can just export util.inherits and use it as an internal utility function.

提交回复
热议问题