本文實(shí)例講述了nodejs基礎(chǔ)之常用工具模塊util用法。分享給大家供大家參考,具體如下:
util是nodejs的核心模塊,提供常用函數(shù)的集合,用戶彌補(bǔ)核心javascript的功能過于精簡(jiǎn)的不足
util.inherits
是一個(gè)實(shí)現(xiàn)對(duì)象間原型繼承的函數(shù)
javascript的面向?qū)ο筇匦允腔谠偷模c常見的基于類的不同。javascript沒有提供對(duì)象繼承的語言級(jí)別特性,而是通過原型復(fù)制來實(shí)現(xiàn)的。
示例:
var util = require('util');function Father(){ //在構(gòu)造函數(shù)內(nèi)部定義,不能被繼承 this.name = 'base'; //在構(gòu)造函數(shù)內(nèi)部定義,不能被繼承 this.birth = 1991; //在構(gòu)造函數(shù)內(nèi)部定義,不能被繼承 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();我們定義了一個(gè)基礎(chǔ)對(duì)象Father 和一個(gè)繼承自Father 的Son,F(xiàn)ather 在構(gòu)造函數(shù)內(nèi)定義兩個(gè)屬性(name,birth)和一個(gè)函數(shù)(sayHello);在原型中定義一個(gè)屬性(age)和兩個(gè)函數(shù)(showName,showAge),通過util.inherits 實(shí)現(xiàn)繼承。
注意:
Son僅僅繼承了Father 在原型中定義的函數(shù),而構(gòu)造函數(shù)內(nèi)部創(chuàng)造的 Father 屬 性和 sayHello 函數(shù)都沒有被 Son繼承。
同時(shí),在原型中定義的屬性不會(huì)被console.log 作 為對(duì)象的屬性輸出。
util.inspect
util.inspect(object,[showHidden],[depth],[colors])是一個(gè)將任意對(duì)象轉(zhuǎn)換 為字符串的方法,通常用于調(diào)試和錯(cuò)誤輸出。它至少接受一個(gè)參數(shù) object,即要轉(zhuǎn)換的對(duì)象。
特別要指出的是,util.inspect 并不會(huì)簡(jiǎn)單地直接把對(duì)象轉(zhuǎn)換為字符串,即使該對(duì) 象定義了toString 方法也不會(huì)調(diào)用。
示例:
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));結(jié)果:
{ name: 'byvoid', toString: [Function] }
新聞熱點(diǎn)
疑難解答
圖片精選