JavaScript中实用、正确的继承
我对JavaScript非常陌生,我认为一个好的任务应该是通过示例处理Kent Beck的TDD,并用JavaScript而不是Java来完成。简单继承似乎很神秘,因为关于如何实现这一点,有很多观点,例如stackoverflow条目: 我不想在C++/Java中模仿继承,即使我最终使用了一个库,我也想知道如何正确地实现它。请看一下以下用JavaScript和Jasmine重写的TDD中的简单货币示例,忽略代码的琐碎性,告诉我这是否是一种合适的技术JavaScript中实用、正确的继承,javascript,inheritance,jasmine-node,Javascript,Inheritance,Jasmine Node,我对JavaScript非常陌生,我认为一个好的任务应该是通过示例处理Kent Beck的TDD,并用JavaScript而不是Java来完成。简单继承似乎很神秘,因为关于如何实现这一点,有很多观点,例如stackoverflow条目: 我不想在C++/Java中模仿继承,即使我最终使用了一个库,我也想知道如何正确地实现它。请看一下以下用JavaScript和Jasmine重写的TDD中的简单货币示例,忽略代码的琐碎性,告诉我这是否是一种合适的技术 // currency.js var Com
// 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/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);
});
});
});
谢谢。在JavaScript中执行继承的最佳方法是避免继承。这通常是不必要的,而且使其工作的内置实用程序都没有很大帮助。你总是可以把它和ES5特性结合在一起,但即使这样,在JS中坚持一种功能性更强的编程风格通常也更容易。我不同意应该避免这种做法。有些地方它可能非常有用。不是每一个地方,而是每一个地方。你可能想看看。美元和英镑不一样吗?在这一点上,是的。