您的位置:首页 > Web前端 > Node.js

Node.js 实用工具

2016-06-10 18:02 453 查看
为了弥补核心JavaScript 的功能的不足,node.js为我们提供了一个工具模块“util”。


1.引入工具

var util = require('util');


1.util.inherits(constructor, superConstructor)

util.inherits(constructor, superConstructor)是一个实现对象间原型继承 的函数。JavaScript 的面向对象特性是基于原型的,
与常见的基于类的不同。JavaScript 没有提供对象继承的语言级别特性,而是通过原型复制来实现的。示例:


var util = require('util');
function People() {
this.name = 'people';
this.age = 0;
this.sayHello = function() {
util.log(this.name + " say hello.");
};
}
People.prototype.showName = function() {
util.log(this.name);
};
function Student() {
this.name = 'student';
this.age = 18;
}
var people = new People();
people.showName();
people.sayHello();
util.log(people);

util.inherits(Student, People);
var student = new Student();
student.showName();
//student.sayHello();
util.log(student);


运行结果:
12 Jun 13:24:40 - people
12 Jun 13:24:40 - people say hello.
12 Jun 13:24:40 - People { name: 'people', age: 0, sayHello: [Function] }
12 Jun 13:24:40 - student
12 Jun 13:24:40 - Student { name: 'student', age: 18 }

注意:Student仅仅继承了People在原型中定义的函数,如果将注释打开则显示如下
student.sayHello();
^
TypeError: student.sayHello is not a function
at Object.<anonymous> (C:\...\util.js:24:9)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3


2.util.inspect(object[, options])

object < any > 任何js代码或者对象

options < Object >

showHidden < boolean >如果true, 这个类的非原型标志和属性将在结果中显示。默认是false

depth < number > 表示最大递归的层数,如果对象很复杂,你可以指定层数以控制输出信息的多少。如果不指定depth,默认会递归2层,指定为 null 表示将不限递归层数完整遍历对象。

colors < boolean > 如果color 值为 true,输出格式将会以ANSI 颜色编码,默认是false。颜色是可以定制的, 详见Customizing util.inspect colors

customInspect < boolean > 如果为 false, 自定义的inspect(depth, opts) 将不再启作用. 默认为 true

maxArrayLength < number > 元素显示的最大数目,默认100,设置为null表示显示所有的元素,设置0或negative表示不显示

3.util.isArray(object)

判断object是否是数组(已废弃),现在建议使用Array.isArray()


4.util.isDate(object)

判断是否是日期


2.备注

util中还有很多util.isXXX的方法,多数已废弃,详见


util官方文档
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node.js util