本篇,我们介绍下node中 util模块 util对象的使用。
util 一个非常小巧的工具,util.inherits(sub,super)用于构建父子继承关系,util.inspect(obj)用于探测对象内部信息,它返回的是一个有趣可靠的字符串(并不是对象的toString方法返回的字符串),在日常开发调试中会非常有用。
08_node_util.js
//08_node_util.js //介绍nodejs中一些 常用的工具类的使用 // util.inherits util.inspect var util = require('util'); function Person(props) { this.name=props.name; this.age=props.age; this.sayHello=function () { console.log("hello: my name is "+this.name+", and I am "+this.age+" years old"); } } Person.prototype.showMe=function () { console.log("你好,我是"+this.name+",我今年"+this.age+'岁了'); }; var person=new Person({name:'zhangsan',age:22}); // person.sayHello(); // person.showMe(); function Student(props) { this.name=props.name; this.age=props.age; this.grade=props.grade; this.m=function () { console.log("haha"); } } Student.prototype.showGrade=function () { console.log('我的学习成绩是:'+this.grade); }; //这里传入的是子、父类构造函数。让Student类继承Person类 util.inherits(Student, Person); var student=new Student({name:'lisi',age:24,grade:98}); student.showGrade();//Person 原型中的方法 student.showMe();//Student 原型中的方法 student.m();//Student 构造函数中定义的方法 console.log(util.inspect(student)); //在nodejs 开发中我们可以使用util.inspect(student, true) 获得对象的更详细的信息(比console.log更详细) console.log(util.inspect(student, true)); // util.isArray(object) // 如果给定的参数 "object" 是一个数组返回true,否则返回false。 // // util.isRegExp(object) // 如果给定的参数 "object" 是一个正则表达式返回true,否则返回false。 // // util.isRegExp(object) // 如果给定的参数 "object" 是一个正则表达式返回true,否则返回false。 // // util.isDate(object) // 如果给定的参数 "object" 是一个日期返回true,否则返回false // // util.isError(object) // 如果给定的参数 "object" 是一个错误对象返回true,否则返回false。
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1