我正在使用node.js(+ angular等)构建一个Web应用程序。
该应用程序将必须从不同的提供者那里检索一些数据(诸如目录项列表),这些提供者以不同的方式公开其数据。
在该模块中,我将拥有所有提供程序都共有的某些功能,以及其中任何一个都独有的功能。
我当前(较差)的实现是这样的:
var providers = [
{ name: 'Apple', /* ... */ },
{ name: 'Samsung', /* ... */ },
{ name: 'Google', /* ... */ },
];
exports.syncCatalogues = function(search, callback) {
var allItems = [];
for (var p = 0; p < providers.length; p++) {
exports.getCatalog(providers[p], function(err, catalog) {
if (err) {
return callback(err);
}
exports.getItems(providers[p], catalog, function(err, items) {
if (err) {
return callback(err);
}
allItems = allItems.concat(items);
callback(null);
});
});
}
};
Run Code Online (Sandbox Code Playgroud)
我的getCatalog()和getItems()实现是如此丑陋:
exports.getCatalog(provider, callback) {
if (provider.name === 'Apple') {
// code for Apple provider ...
}
// and so on ...
};
exports.getItems(provider, callback) {
if (provider.name === 'Apple') {
// code for Apple catalog ...
}
// and so on ...
};
Run Code Online (Sandbox Code Playgroud)
我知道使用ES5(我坚持使用它)不容易实现抽象类,但是我敢肯定有比这更好的方法(代码更具可读性,可维护性,可测试性)... :-(
在 JavaScript 中实现继承的方法有很多种。这是一个,我认为最简单的,因为您只操作普通对象并使用原型继承。
您有一个原型对象,而不是基类,您可以在其中放置公共代码。然后根据原型创建一个对象并向其添加特定代码。
var providerPrototype = {
name: 'Prototype',
alertName: function() { // this is common function, all objects
alert(this.name); // will have it
}
};
var appleProvider = Object.create(providerPrototype);
appleProvider.name = 'Apple';
// this is a specific function for 'Apple'
appleProvider.getCatalog = function(callback) {
return callback(null, ['iPhone', 'Mac Mini']);
}
appleProvider.alertName = function() {
// call 'base' method
providerPrototype.alertName.call(this);
alert('All rights reserved.');
}
var samsungProvider = Object.create(providerPrototype);
samsungProvider.name = 'Samsung';
// this is a specific function for 'Samsung'
samsungProvider.getCatalog = function(callback) {
return callback(null, ['Galaxy S3', 'Galaxy S4']);
}
var providers = [
appleProvider, samsungProvider
];
var syncCatalogues = function(search, callback) {
var allItems = [];
for (var p = 0; p < providers.length; p++) {
var aProvider = providers[p];
aProvider.getCatalog(function(err, catalog) {
if (err) {
return callback(err);
}
aProvider.alertName(); // call the base method
alert(catalog);
});
}
};
syncCatalogues();
Run Code Online (Sandbox Code Playgroud)
还要检查Mozilla javascript 文档中的继承和原型链。
归档时间: |
|
查看次数: |
4460 次 |
最近记录: |