util

util.inherits

util.inherits(constructor,superConstructor)是一個實現對象間原型繼承的函數。

示例如下:

var util=require('util');
function Base(){
    this.name='base';
    this.base=2016;

    this.sayHello=function(){
        console.log('Hello'+this.name);
    };
}

Base.prototype.showName=function(){
    console.log(this.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();
console.log(objSub);

運行結果:

base
Hellobase
Base { name: 'base', base: 2016, sayHello: [Function] }
sub
Sub { name: 'sub' }

需要注意的是,Sub僅僅繼承了Base在原型中定義的函數,而構造函數內部創造的base屬性和sayHello函數都沒有被Sub繼承。同時,在原型中定義的屬性不會被console.log作爲對象的屬性輸出。

util.inspec

util.inspect(object,[showHidden],[depth],[colors])是一個將任意對象轉換爲字符串的方法,通常用於調試和錯誤輸出。

object:必選參數,即要轉換的對象。

showHidden:可選,如果值爲true,將會輸出更多隱藏信息。

depth:表示最大遞歸的層數,如果對象很複雜,你可以指定層數以控制輸出信息的多少。如果不指定depth,默認會遞歸兩層,指定爲null表示將不限制遞歸層數完整遍歷整個對象。

color:如果職位true,輸出格式將會以ANSI顏色編碼,終端會顯示出更加漂亮的效果。

注意:使用util.inspect方法時,即使該對象定義了toString方法,也不會調用。

var util=require('util');
function Person(){
    this.name='Bob';
    this.toString=function(){
        return this.name;
    };
}

var obj=new Person();

console.log(util.inspect(obj));
console.log(util.inspect(obj,true));
console.log(util.inspect(obj,true,4,true));

運行結果:

inspect.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章