1 創(chuàng)建基類base.js
function Base(){
????if(!(this instanceof Base)){
? ? ? ? return new Base();
? ? }
? ? this.baseVar = "base var";
? ? Base.prototype.baseMethod = function(){
? ? ? ? console.log("base method");
? ? ? ? console.log("base var:"+this.baseVar);
? ? }
}
module.exports = Base;
2 創(chuàng)建子類child.js
var Base = require('./base');
var util = require('util');
function Child(){
? ? if(!(this instanceof Child)){
? ? ? ? return new Child();
? ? }
? ? this.childVar = "child var";
? ? Child.prototype.childMethod = function(){
? ? ? ? console.log("child method");
? ? ? ? console.log("child var:"+this.childVar);
? ? }
}
util.inherits(Child, Base);
module.exports = Child;
3 調(diào)用app.js
var base = require('./base');
var child = require('./child');
var baseObj = new base();
baseObj.baseMethod();
child.baseMethod();
child.childMethod();
運(yùn)行
# node app.js
輸出
base method
base var:base var
base method
base var:undefined
child method
child var:child var