node.js提供了很多模塊,其中util就是nodejs核心模塊之一,主要就是爲了彌補js過於精簡而造成的不足。
1. util.inherits
util.inherits(constructor, superConstructor)是用來實現對象間原型繼承的函數
舉個栗子說明一切
const util = require("util");
function one() {
this.name = "one";
this.one = "111";
this.sayWho = function () {
console.log("我是"+this.name);
}
}
one.prototype.sayHello = function () {
console.log(this.name);
};
function two() {
this.name = "two";
}
util.inherits(two,one);
var oneobj = new one();
oneobj.sayHello();//one
oneobj.sayWho();//我是one
console.log(oneobj);//one { name: 'one', one: '111', sayWho: [Function] }
var twoobj = new two();
twoobj.sayHello();//two
twoobj.sayWho();//twoobj.sayWho is not a function
這裏我要說下,這個two函數只繼承了,one函數的原型中定義的函數,其他的都沒有繼承
2. util.inspect
util.inspect(object,[showHidden],[depth],[colors])是一個將任意對象轉換爲字符串的方法,通常用於調試和錯誤輸出。
該方法最少接受一個參數object,showHidden可選,當值爲true時,會打印出更多隱藏 的信息。depth是最大遞歸層數。
可以指定層數,控制輸出的信息,color爲true 的時候,將以ANSI 顏色編碼輸出。
const util = require('util');
function demo() {
this.name = 'helloDemo';
this.toString = function() {
return this.name;
};
}
var d = new demo();
console.log(util.inspect(d));
console.log(util.inspect(d, true));
3. util.isArray
util.isArray(object),傳一個參數,如果是數組返回true,else就返回false
var util = require('util');
util.isArray([])// true
util.isArray(new Array)// true
util.isArray({}) // false
不用多說這個就是判斷是不是數組
4. util.isRegExp
util.isRegExp(object),傳一個參數,如果是正則表達式返回true,else就返回false
var util = require('util');
util.isRegExp(/some regexp/)// true
util.isRegExp(new RegExp('another regexp')) // true
util.isRegExp({})// false
此處省略幾個字
5. util.isDate
util.isDate(object),傳一個參數,如果是日期返回true,else就返回false
var util = require('util');
util.isDate(new Date())// true
util.isDate(Date())// false (without 'new' returns a String)
util.isDate({}) // false
我覺得這個也不用說
6. util.isError
util.isError(object) 傳一個參數,如果是錯誤對象返回true,else就返回false。
var util = require('util');
util.isError(new Error()) // true
util.isError(new TypeError())// true
util.isError({ name: 'Error', message: 'an error occurred' })// false
鄙人拙見,如有出入,勞煩指點,謝謝