在网上有很多关于组合与继承的信息,但我没有找到适用于JavaScript的好例子。使用以下代码来演示继承:
function Stock( /* object with stock names and prices */ ) {
for (var company_name in arguments[0]) {
// copy the passed object into the new object created by the constructor
this[company_name] = arguments[0][company_name];
}
}
// example methods in prototype, their implementation is probably redundant for
// this question, but list() returns an array with toString() invoked; total()
// adds up the stock prices and returns them. Using ES5 feature to make
// inherited properties non-enumerable
Stock.prototype = {
list: function () {
var company_list = [];
for (var company_name in this)
company_list.push(company_name);
return company_list.toString();
},
total: function () {
var price_total = 0;
for (var company_name in this)
price_total += this[company_name];
return '$' + price_total;
}
};
Object.defineProperties(Stock.prototype, {
list: { enumerable: false },
total: { enumerable:false }
});
var portfolio = new Stock({ MSFT: 25.96, YHOO: 16.13, AMZN: 173.10 });
portfolio.list(); // MSFT,YHOO,AMZN
portfolio.total(); // $215.19
(为了让代码更简洁,您可以省略方法实现,例如:Stock.total = function(){ /* 代码 */ }
。我只是在这里放置它们以增加可读性)。如果在面向对象编程中,组合方式被广泛采用,那么为什么大多数使用JavaScript的人似乎只使用原型和继承?我在网上没有找到关于JavaScript中组合的很多信息,只有其他语言。
有人能给我举个例子来演示组合和聚合吗?