node.js中的核心模块util的方法(util.inherits,util.inspect,util.isArray(),util.isRegExp())

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

鄙人拙见,如有出入,劳烦指点,谢谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值