美文网首页
nodejs 面向对象-继承

nodejs 面向对象-继承

作者: 闭上说 | 来源:发表于2018-01-18 10:09 被阅读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

    相关文章

      网友评论

          本文标题:nodejs 面向对象-继承

          本文链接:https://www.haomeiwen.com/subject/kqpioxtx.html