我对JavaScript非常陌生,并认为一个好的任务将通过Kent Beck的TDD By Example工作,并用JavaScript代替Java。简单的继承似乎很神秘,因为有很多关于如何实现这一点的意见,例如这个stackoverflow条目:JavaScript Inheritance
我不想在C ++ / Java中模仿继承,即使我最终使用了库,我也想知道如何自己正确地实现它。请查看以下简单的货币示例,该示例来自在JavaScript和Jasmine中重写的TDD By Example,并且忽略代码的微不足道,请告诉我这是否是一种正确的技术。
// currency.js
var CommonCurrency = function() {
function Currency(amount){
this.amount = amount;
}
Currency.prototype.times = function(multiplier){
return new Currency(this.amount*multiplier);
};
function Dollar(amount){
Currency.call(this, amount);
}
Dollar.prototype = Object.create(Currency.prototype);
Dollar.prototype.constructor = Dollar;
function Pound(amount){
Currency.call(this, amount);
}
Pound.prototype = Object.create(Currency.prototype);
Pound.prototype.constructor = Pound;
return {
Dollar: Dollar,
Pound: Pound
}
}();
module.exports = CommonCurrency;
spec文件:
// spec/currency-spec.js
var currency = require("../currency");
describe("testCurrency", function() {
describe("testDollar", function() {
var fiveDollars = new currency.Dollar(5);
it("should multiply dollar amount by given parameter", function() {
var product = fiveDollars.times(2);
expect(product.amount).toBe(10);
});
it("should return new dollar amount and not multiply last result ", function() {
var product = fiveDollars.times(3);
expect(product.amount).toBe(15);
});
});
describe("testPound", function() {
var fivePounds;
it("should multiply pound amount by given parameter", function() {
var product = fivePounds.times(2);
expect(product.amount).toBe(10);
});
it("should return new pound amount and not multiply last result ", function() {
var product = fivePounds.times(3);
expect(product.amount).toBe(15);
});
});
});
感谢。