我通常使用一个defclass
效用函数中的JavaScript来定义“类”:
function defclass(base, body) {
var uber = base.prototype;
var prototype = Object.create(uber);
var constructor = (body.call(prototype, uber), prototype.constructor);
constructor.prototype = prototype;
return constructor;
}
然后我用它如下:
var A = defclass(Object, function() {
this.constructor: function (arg1, arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
this.log = function (which) {
console.log(which ? this.arg1 : this.arg2);
};
});
继承是死的简单:
var B = defclass(A, function (uber) {
this.constructor = function (arg1, arg2, arg3) {
uber.constructor.call(this, arg1, arg2);
this.arg3 = arg3;
};
this.log = function (which) {
uber.log.call(this, which);
console.log(this.arg3);
};
});
正如你可以当我们延伸的“类”看到我们使用Object.create
。这是继承的新方式。使用new
是陈旧的。在B
构造我们通过参数的A
使用uber.constructor.call
构造。
如果你喜欢这种模式,那么你应该看看augment库。
确实有趣的图书馆。但是我不喜欢用'this.prop = value;'来定义属性和方法。 – Tot