util 是一个 Node.js 核心模块,提供常用函数的集合,用于弥补核心 JavaScript 的功能 过于精简的不足。
util.inherits
util.inherits(constructor, superConstructor) 是一个实现对象间原型继承的函数。
JavaScript 的面向对象特性是基于原型的,与常见的基于类的不同。JavaScript 没有提供对象继承的语言级别特性,而是通过原型复制来实现的。
在这里我们只介绍 util.inherits 的用法,示例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| var util = require("util") function Base() { this.name = "base" this.base = 1991 this.sayHello = function () { console.log("Hello " + this.name) } } Base.prototype.showName = function () { console.log(this.name) } function Sub() { this.name = "sub" } util.inherits(Sub, Base) var objBase = new Base() objBase.showName() objBase.sayHello() console.log(objBase) var objSub = new Sub() objSub.showName()
console.log(objSub)
|