请教关于require和继承的问题
发布于 11 年前 作者 cuimuxi 5754 次浏览 最后一次编辑是 8 年前

我现在想写一个模块,由于模块逻辑相对复杂,模块内部有很多文件,我使用类似OOP方式来组织这个模块,比如一个父类下面有N个子类,这些子类和父类之间仅仅是一些细致行为不同 Node中使用exports和require可以得到父类的对象,那么继承的代码是怎么写的呢?

示例代码如下:

person.js

Person = function () {
	
}

Person.prototype.hello = function () {
		console.log('I am Person');
}

exports.Person = Person;

student.js

var person = require('./person');
var util = require('util');


function Student () {
	person.call(this);
}

util.inherits(Student, person);


Student.prototype.say = function() {
	console.log('I am student');
}


exports.Student = Student;

test.js

person = require('./person');
student = require('./student');


person.hello();
student.hello();
student.say();

这个基本上参照 http://cnodejs.org/topic/4fbae57dd46624c476072445 这个帖子来实现的,很诡异的报错了,求指导

util.js:538 ctor.prototype = Object.create(superCtor.prototype, { ^ TypeError: Object prototype may only be an Object or null at Function.create (native) at Object.exports.inherits (util.js:538:27)

9 回复

var person = require(’./person’).person

感谢回复,这个似乎解决了上一个报错,但是貌似没继承成功,在test中调用student.hello()时报这个方法不存在

明白了,test中应该new这个对象

最后test中代码这样可以运行

person = require('./person');
student = require('./student');

p = new person.Person;
p.hello();

s = new student.Student
s.hello();
s.say();

什么样情况下需要new操作,什么样情况直接require就能用呢?为什么有些不用new呢,比如内置的http.xxx()就能工作

  • 你需要从一个构造函数对象(function{})构造一个对象的时候就得用new
  • 呃,你是不是对js和node.js不熟啊?建议先了解一下require机制,以及exports和module.exports

我的理解:

不用 new,就没有 新的对象(instance)产生,就没有 this, 就没有 prototype, 就没有继承的函数。因为继承的函数都在对象的 prototype 里面。

@sumory 确实对Node.js不熟,以前零星写过一些不大不小的JS代码,以前都是用Python,PHP等,正在尝试使用Node解决生产环境的实际问题,感谢耐心回复

呃,这个,其实没有new,也有this和prototype的

http.createServer()相当于一个快捷方式,内部是有new Server()的,你可以看一下它的源码

@sumory 对,没有new, this好象就指到全局那个域上了。

回到顶部