如何解决javascript中的继承问题
| 我有以下类层次结构: 存储 采集 EixoCollection OfertaCollection 我有以下代码:var ofertaCollection = new OfertaCollection();
var eixoCollection = new EixoCollection();
ofertaCollection.set(\'mykey\',\'myvalue\');
alert(eixoCollection.get(\'mykey\')); // it returns \'myvalue\',should return nothing
问题是ofertaCollection和eixoCollection具有互相引用的属性。
遵循课程:
/**
* Storage
*
* @returns {Storage}
*/
function Storage(){
this.storage = []; // itens that have a key
// sets key
this.set = function(key,value){
this.storage[key] = value;
}
// gets key
this.get = function(key){
return this.storage[key];
}
}
/**
* Collection
*
* @returns {Collection}
*/
function Collection(){
}
Collection.prototype = new Storage();
/**
* EixoCollection
*
* @returns {EixoCollection}
*/
function EixoCollection(){
}
EixoCollection.prototype = new Collection();
/**
* OfertaCollection
*
* @returns {OfertaCollection}
*/
function OfertaCollection(){
}
OfertaCollection.prototype = new Collection();
问题是什么?
解决方法
首先,我建议对代码进行两个更改(示例将使用):
this.storage
应该是对象{}
,因为看起来好像您从未将其用作数组。另外,原型中应包含get
和set
,否则将为每个实例对象创建这些方法的新实例(除非智能编译器对其进行优化,但我们不会做太多假设)。
解决方案1:您可以执行准继承,即仅将存储方法提供给继承的类,而不提供存储对象:
function Storage(){}
storage.prototype = {
get: function(key){
return this.storage[key];
},set: function(key,value){
this.storage[key] = value;
}
};
function Collection(){
this.storage = {};
}
Collection.prototype = Storage.prototype; // quasi-inheritance
function EixoCollection(){}
EixoCollection.prototype = new Collection();
function OfertaCollection(){}
OfertaCollection.prototype = new Collection();
var ofertaCollection = new OfertaCollection();
var eixoCollection = new EixoCollection();
ofertaCollection.set(\'mykey\',\'myvalue\');
alert(eixoCollection.get(\'mykey\')); // undefined
解决方案2:真正的继承,但是为每个集合实例化一个新存储,因此在原型查找过程中,该函数将查找本地存储。这与上面的相同,但是继承与以前相同。因此,我将替换不同的行:
Collection.prototype = new Storage(); // real inheritance
这两个实现的问题在于,它们需要继承的类来做两件事,既继承方法,又实例化存储。不漂亮。
一种简单的选择,也许是最直观的选择,是将Storage
的每种用法都制成一个复合对象,而不是一个继承的对象。集合具有内部存储器和一些其他功能,因此它使具有助记符的组合成为有效的候选者。
, 问题在于两个集合对象都共享相同的“ 8”对象。
var c1 = new OfteraCollection().prototype.prototype;
var c2 = new ExioCollection().prototype.prototype;
console.log(c1 === c2); // true
为了解决这个问题,您可以将所有的Collection
一起扔掉,并让每个集合对象创建自己的Storage
作为其原型。
, 这是非常快速的解决方法-更改:
function Collection(){
// assuming you\'re doing some initialization here,referencing \"this\"
}
Collection.prototype = new Storage();
至
function Collection(){
var that = new Storage();
// initialize whatever\'s necessary,using \"that\"
return that;
}
或者,如果您不进行任何初始化,则只需:
function Collection(){
return new Storage();
}
这里的工作示例。
这样会将ѭ11变成Storage
工厂,从而防止了在子孙中重复使用相同的Storage
对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。