var util = require('util');
functionPeople() {this.name = 'people';
this.age = 0;
this.sayHello = function() {
util.log(this.name + " say hello.");
};
}
People.prototype.showName = function() {
util.log(this.name);
};
functionStudent() {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