我正在嘗試幾種不同的方法來Javascript的繼承此刻。我有以下代碼:Javascript繼承
(從http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm '借')
KV = {};
KV.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}
function GridView() {
var _ownerElement;
}
GridView.prototype.getOwnerElement = function() {
return this._ownerElement;
}
GridView.prototype.setOwnerElement = function(ownerElement) {
this._ownerElement = ownerElement;
}
GridView.prototype.initialize = function() {
this.setOwnerElement('test');
}
function StreetGridView(dataURL, ownerElement) {
StreetGridView.baseConstructor.call(this);
StreetGridView.superClass.initialize();
StreetGridView.superClass.setOwnerElement(ownerElement);
}
// subclass StreetGridView
KV.extend(StreetGridView, GridView);
現在,當我創建StreetGridView的一個實例,我可以調用它getOwnerElement()沒有問題。一切都按預期工作。
無論其
當我創建另一個實例,到實例2所做的任何更改都反映回實例1
我知道這是用原型作爲共享實例信息的主要問題。今天早上我一直在絞盡腦汁,但是想知道是否有人能夠指引我走向正確的方向!
謝謝
在這裏找到答案:http://stackoverflow.com/a/12816953/885464 – 2015-11-05 12:16:03