本文实例讲述了nodejs基础之常用工具模块util用法。分享给大家供大家参考,具体如下:
util是nodejs的核心模块,提供常用函数的集合,用户弥补核心javascript的功能过于精简的不足
util.inherits
是一个实现对象间原型继承的函数
javascript的面向对象特性是基于原型的,与常见的基于类的不同。javascript没有提供对象继承的语言级别特性,而是通过原型复制来实现的。
示例:
var util = require('util');function Father(){ //在构造函数内部定义,不能被继承 this.name = 'base'; //在构造函数内部定义,不能被继承 this.birth = 1991; //在构造函数内部定义,不能被继承 this.sayHello = function(){ console.log('hello'+this.name); }}//在原型中定义,可以被继承Father.prototype.age=18;//在原型中定义,可以被继承Father.prototype.showName = function(){ console.log(this.name); console.log(this.age);}//在原型中定义,可以被继承Father.prototype.showAge = function(){ console.log(this.age);}function Son(){}util.inherits(Son,Father);var objBase = new Father();objBase.showName();objBase.sayHello();console.log(objBase);var objSub = new Son();objSub.showAge();
我们定义了一个基础对象Father 和一个继承自Father 的Son,Father 在构造函数内定义两个属性(name,birth)和一个函数(sayHello);在原型中定义一个属性(age)和两个函数(showName,showAge),通过util.inherits
实现继承。
注意:
Son仅仅继承了Father 在原型中定义的函数,而构造函数内部创造的 Father 属 性和 sayHello 函数都没有被 Son继承。
同时,在原型中定义的属性不会被console.log 作 为对象的属性输出。
util.inspect
util.inspect(object,[showHidden],[depth],[colors])
是一个将任意对象转换 为字符串的方法,通常用于调试和错误输出。它至少接受一个参数 object,即要转换的对象。
特别要指出的是,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] }
新闻热点
疑难解答
图片精选