【发布时间】:2014-06-15 14:53:02
【问题描述】:
我正在尝试在 Knockout 中进行类继承以应用 DRY 原则,但还没有 非常成功。
我想要实现的是两种类型的服务器,它们具有一些相似之处,而无需重复代码或大量代码。
这是我最新的尝试,有些功能无法正常工作。
父类:
function BaseServer(options, builder) {
this.formatted_price = ko.computed(function() {
return utils.format_price(this.price(), options.prices.currency());
}, this);
this.drives = ko.observableArray([]);
this.number_of_instances = ko.observable(1);
// Not sure if this is a good approach for this problem
for (i = 0; i < options.ssd.length; i++) {
self.drives.push(new builder.ssd(options.ssd[i], options.prices));
}
for (i = 0; i < options.hdd.length; i++) {
self.drives.push(new builder.hdd(options.hdd[i], options.prices));
}
// Will not work there is not this.cpu nor this.ram
this.price = ko.computed(function() {
var total = 0
total += this.cpu.price();
total += this.ram.price();
total += _.reduce(this.drives(), function(mem, drive) {
return drive.price();
}, 0);
return total;
}, this);
}
我认为不对的地方:
- 价格函数不起作用,因为父级无法访问 ram、cpu 变量。
- 在我看来,builder 方法是一种非常奇怪的方法,但它确实有效。
- 我在参数选项中传递函数,然后由类调用。
然后是孩子们。
function ServerGama(options){
// Constructors for disks
var builder = {
ssd: SsdGama,
hdd: HddGama
},
self = this;
ko.utils.extend(self, new BaseServer(options, builder));
// Normal attributes
self.cpu = new CpuGama(options.cpu.up, options.cpu.down, options.prices);
self.ram = new RamGama(options.ram.up, options.ram.down, options.prices);
}
function ServerBeta(options){
var builder = {
ssd: SsdBeta,
hdd: HddBeta
},
self = this;
ko.utils.extend(self, new BaseServer(options, builder));
// Normal attributes
self.cpu = new CpuBeta(options.cpu, options.prices);
self.ram = new RamBeta(options.ram, options.prices);
self.licenses = new server_licenses([
{
'name': 'Server 2008',
'price': options.prices.cost_per_2008
},
{
'name': 'Server 2009',
'price': options.prices.cost_per_2009
}
], options.prices.currency, options.choice);
// This price does not seem to overwrite BaseServer price
this.price = ko.computed(function() {
// This will not work because we are losing the biding that price is making to the cpu, ram, disk variables
var total = this.price.call(this);
total += self.licenses.price();
return total;
}, 0);
}, this);
}
我认为不对的地方:
- 来自父级的 formatted_price 不会使用来自 BetaServer 类的这种覆盖。
- 也许我可以用另一种方式构建磁盘
【问题讨论】:
标签: javascript inheritance knockout.js overriding prototype