nodejs 面向对象-继承

2018-01-18  本文已影响0人  闭上说

1 创建基类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 创建子类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 调用app.js

var base = require('./base');

var child = require('./child');

var baseObj = new base();

baseObj.baseMethod();

child.baseMethod();

child.childMethod();

运行

# node app.js

输出

base method

base var:base var

base method

base var:undefined

child method

child var:child var

上一篇下一篇

猜你喜欢

热点阅读