Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,495,102字

该文章投稿至Nemo社区   Js、Css、Html  板块 复制链接


[NodeJS]Util.inherits,原型继承

发布于 2016/06/17 00:06 2,355浏览 0回复 914

//引入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);
点赞(0)
点了个评