我有这个功能:(我猜这是用于创建 javascript 对象的抽象工厂)
var $class = function(definition) {
var constructor = definition.constructor;
var parent = definition.Extends;
if (parent) {
var F = function() { };
constructor._superClass = F.prototype = parent.prototype;
constructor.prototype = new F();
}
for (var key in definition) {
constructor.prototype[key] = definition[key];
}
constructor.prototype.constructor = constructor;
return constructor;
};
使用它来定义类 C/java 语法,如多态和扩展:
var Bullet = $class({
Extends: GameObject,
constructor: function(texturePath, x, y, ctx, direction, passable, player) {
GameObject.call(this, texturePath, x, y, ctx, 1, 1, passable, new Array(8, 8, 0, 0));
},
isActive: function() {
},
getPlayer: function() {
},
update: function(dt) {
},
destroy: function() {
},
processCollision: function() {
}
});
然后调用:
var bullet = new Bullet(params);
我尝试将其重写为 nodejs 模块,如下所示:
(function(){
var $class = function(definition) {
var constructor = definition.constructor;
var parent = definition.Extends;
if (parent) {
var F = function() { };
constructor._superClass = F.prototype = parent.prototype;
constructor.prototype = new F();
}
for (var key in definition) {
constructor.prototype[key] = definition[key];
}
constructor.prototype.constructor = constructor;
return constructor;
};
module.exports.createClass = function() {
return $class();
}
});
然后调用它:
var c = require(__dirname + "\\Class");
var Bullet = c.createClass({
Extends: GameObject,
constructor: function() {}
});
但它不起作用,你能帮我重写吗?
更新:我从@Salem 的答案重写了它,但我在过程中失去了扩展和多态性。为了扩展我只需要写而不是
Extends: ParentClass
这个:
Extends: ParentClass.constructor
我预计多态性会是这样的:
// in class which is extended from ParentClass
ParentClass.method();
// in parent class adding line
module.exports.method = ParentClass.method;
但这是未定义的。那么问题在哪里呢?
最后,我为 nodejs 使用了 mochiscript 模块,它是更好的语法糖,具有更多面向对象的功能。