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官方文档
相关文章推荐
- 使用 HTTP 上传 G 级的文件之 Node.js 版本
- mongo实现消息队列
- Node.js压缩web项目中的js,css和图片
- node连接mysql数据库
- 使用 Node.js 构建交互式命令行工具
- async.js 学习记录
- 异步流程控制:7 行代码学会 co 模块
- 新时代编辑神器:Atom
- rem : web app适配的秘密武器
- jquery高级应用之Deferred对象
- ndm:NPM 的桌面 GUI 程序
- node.js中的fs.mkdir方法使用说明
- 为什么Node.js会这么火呢?Node.js流行的原因
- 究竟什么是Node.js?Node.js有什么好处?
- Linux下为Node.js程序配置MySQL或Oracle数据库的方法
- 三种Node.js写文件的方式
- node.js中的http.response.removeHeader方法使用说明
- 快速掌握Node.js模块封装及使用
- Node.js文件操作方法汇总
- Nodejs爬虫进阶教程之异步并发控制