javascript - 有没有办法在已经存在的构造函数中拥有一个构造函数?
问题描述
我有以下作为基本构造函数的函数:
function Foo() = {}
...
exports Foo
它是一个空的构造函数,由我不想更改的其他函数使用。此外,Foo
仅从文件中导出。
现在我可能需要在Foo
.
以下是我enum
作为独立构造函数所拥有的。但是我如何让它成为其中的一部分Foo
呢?
function enum(data) {
this.data = data
}
enum.prototype.getVal() { return this.data; }
var obj = new enum(5);
obj.getVal();
解决方案
从您的 commnets 中进行完全疯狂的猜测。
从文件中导出并不重要。如果您只是Foo
用作命名空间来“挂起”功能,则可以这样做:
枚举.js
// all constructors should be capitalized
function Enum() { }
Enum.prototype.whatever ...
exports Enum
Foo.js
const Enum = require('./Enum');
// it's unclear why `Foo` is even a function to be honest
function Foo() { }
Foo.Enum = Enum;
exports Foo
一些其他文件.js
const Foo = require('./Foo');
const myEnumInstance = new Foo.Enum();