I'm very new to JavaScript and thought a good assignment would be working through Kent Beck's TDD By Example and doing it in JavaScript instead of Java. Simple inheritance seems to be mystifying as there are many opinions on how to achieve this, such as this stackoverflow entry: JavaScript Inheritance
I don't want to imitate inheritance in C++/Java, and even if I eventually use a library, I want to know how to implement it properly myself. Please look at the following simple currency example from TDD By Example rewritten in JavaScript and Jasmine and, disregarding the triviality of the code, tell me if this is a proper technique.
// 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 file:
// 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);
});
});
});
Thanks.