Inheritable static methods in Node.js?
I have the following structure:
开发者_StackOverflow中文版First file:
Base = function() {
};
Base.something = function() {
return "bla";
};
if (typeof module !== 'undefined' && "exports" in module) {
module.exports = Base;
}
Second file:
var
util = require('util'),
Base = require('./base.js');
FooBar = function() {
};
util.inherits(FooBar, Base);
But FooBar.something
is undefined. How can I inherit static methods in node.js?
util.inherits operates on the prototype of a constructor function.
You need to use a simple mixin, commonly referred to as extend. It basically just copies all the properties of one (or many) objects into a "destination" object. (in this case, your constructor function)
If you're using underscore.js, you can use _.extend(FooBar, Base);
I've found an another solution which is better, because I would use only one library to achieve the same functionality.
This library is the oop by Felix Geisendörfer, he also wrote a tutorial at nodeguide.com but it's outdated a bit. But here is a working example for the same problem:
var
oop = require('oop'),
Base = require('./base.js');
FooBar = function() {
oop.mixin(this, Base);
};
oop.extend(FooBar, Base);
To export static functions in Base, add:
module.exports = Base;
inside Base.js.
精彩评论