节点模块和原型继承

Node Modules and Prototype Inheritance

本文关键字:继承 原型 模块 节点      更新时间:2023-09-26

目前我有:

index.js(在模块foo中)

function Foo(options) {
    this.memberVar = options.memberVar;
}
Foo.prototype.bar = function(word) {
    console.log('word: ', word);
}
module.exports = Foo;

server.js(在单独的模块栏中)

var Foo = require('foo'),
    foo = new Foo(options),
    greeting = 'Hello World!';
foo.bar(greeting); // prints Hello World!

这很好,但我觉得如果我不必使用new关键字实例化一个新的foo对象来公开其成员函数,那么其他人会更漂亮、更容易理解。

所以我想做的是:

var greeting = 'Hello World!',
    foo = require('foo')(options);
foo.bar(greeting); // prints Hello World!

如何修改我当前的foo-index.js,以便能够访问上面代码片段中描述的foo对象?

如果您不希望模块的使用者使用new,您可以公开一个工厂方法:

// index.js (in module foo)
function Foo(options) {
    this.memberVar = options.memberVar;
}
Foo.prototype.bar = function(word) {
    console.log('word: ', word);
}
module.exports = function(options) {
    return new Foo(options);
}

// server.js (in separate module bar) 
var greeting = 'Hello World!',
    foo = require('foo')(options);
foo.bar(greeting); // prints Hello World!

但是,请注意,这可能会大大混淆模块的用户。您的原始模式是被广泛接受的,并且是公开构造函数的首选方式。