本节介绍node.js常用工具util。
util作为node.js的一个核心模块,能够提供常用函数的集合,弥补核心javascript的功能过于精简的不足。
util.inherits(constructor, superconstructor)是一个实现对象间原型继承的函数。
与常见的基于类的不同,javascript的面向对象特性是基于原型的。javascript没有提供对象继承的语言级别特性,而是通过原型复制来实现的。
在这里我们只介绍util.inherits的用法,示例如下:
var util = require('util'); function base() { this.name = 'base'; this.base = 1991; 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和一个继承自base的sub,base有三个在构造函数内定义的属性和一个原型中定义的函数,通过util.inherits实现继承。运行结果如下:
base hello base { name: 'base', base: 1991, sayhello: [function] } sub { name: 'sub' }
注意:sub仅仅继承了base在原型中定义的函数,而构造函数内部创造的base属性和sayhello函数都没有被sub继承。
同时,在原型中定义的属性不会被console.log作为对象的属性输出。如果我们去掉objsub.sayhello(); 这行的注释,将会看到:
node.js:201 throw e; // process.nexttick error, or 'error' event on first tick ^ typeerror: object #<sub> has no method 'sayhello' at object.<anonymous> (/home/byvoid/utilinherits.js:29:8) at module._compile (module.js:441:26) at object..js (module.js:459:10) at module.load (module.js:348:31) at function._load (module.js:308:12) at array.0 (module.js:479:10) at eventemitter._tickcallback (node.js:192:40)
util.inspect(object,[showhidden],[depth],[colors])方法可以将任意对象转换为字符串,通常用于调试和错误输出。它至少接受一个object参数,即要转换的对象。
showhidden是一个可选参数,如果值为true,将会输出更多隐藏信息。
depth表示最大递归的层数,如果对象很复杂,你可以指定层数以控制输出信息的多少。如果不指定depth,则默认递归2层,指定为null时表示将不限递归层数完整遍历对象。 如果color值为true,则输出格式将会以ansi颜色编码,通常用于在终端显示更漂亮的效果。
特别要指出的是,util.inspect并不会简单地直接把对象转换为字符串,即使该对象定义了tostring方法也不会调用。
var util = require('util'); function person() { this.name = 'byvoid'; this.tostring = function() { return this.name; }; } var obj = new person(); console.log(util.inspect(obj)); console.log(util.inspect(obj, true));
运行结果是:
{ name: 'byvoid', tostring: [function] } { tostring: { [function] [prototype]: { [constructor]: [circular] }, [caller]: null, [length]: 0, [name]: '', [arguments]: null }, name: 'byvoid' }
如果给定的参数 "object" 是一个数组返回true,否则返回false。
var util = require('util'); util.isarray([]) // true util.isarray(new array) // true util.isarray({}) // false
如果给定的参数"object"是一个正则表达式返回true,否则返回false。
var util = require('util'); util.isregexp(/some regexp/) // true util.isregexp(new regexp('another regexp')) // true util.isregexp({}) // false
如果给定的参数 "object" 是一个日期返回true,否则返回false。
var util = require('util'); util.isdate(new date()) // true util.isdate(date()) // false (without 'new' returns a string) util.isdate({}) // false
如果给定的参数 "object" 是一个错误对象返回true,否则返回false。
var util = require('util'); util.iserror(new error()) // true util.iserror(new typeerror()) // true util.iserror({ name: 'error', message: 'an error occurred' }) // false
更多详情可以访问 http://nodejs.org/api/util.html 了解详细内容。