精选圈子榜单优站
编程综合
编程综合
技术
20关注
编程技术记录、分享 ,记录你的编程生活点点滴滴!

[NodeJS]Util.inherits,原型继承


//引入util模块
var util = require('util');

//定义函数Base
function Base(){
    //定义全局变量name和year
    this.name = 'Nemo';
    this.year=2016;
    //定义了一个私有的sayHello方法,只能在本函数内使用
    this.sayHello=function (){
        console.log('Hello:'+this.name+'. This year is '+this.year);    
    }
}

//暴露一个Base的showName方法,打印输出全局变量name,只要继承自Base的函数都可以使用
Base.prototype.showName = function (){
    console.log(this.name);
}

//定义另一个函数Sub用来修改全局变量name
function Sub(){
    this.name = 'sub';
}

//原型继承
util.inherits(Sub,Base);

//原有输出
var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);

//继承后的子类输出
var objSub = new Sub();
objSub.showName();
//objSub.sayHello();//Base的私有方法,不可调用
console.log(objSub);

  • 若文章侵犯了您的权益,请联系我们进行处理。

  • 2016-06-17
  • 2743阅读
评论