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));
运行结果: