I have a class designMain
which extends design
.
I have found that if I set an eventListener in design
, when the event is fired, all references to this
will only refer to the non extended design
object. Is there a way to overcome this shortcoming of my extended class?
UPDATE - I've included an ES6 version which works as expected and shows what I am trying to accomplish - namely that this
with extended classes will always refer to the extended class even with code (e.g. addEventListener) within the base class. In this case this.name
should always be from the extended class.
Here is a jsFiddle
HTML
<div id="test">
Design (click will fail)
</div>
<div id="test2">
DesignMain (click will succeed)
</div>
javascript
design = (function() {
function design() {
this.name = "design";
var _this = this;
var e = document.getElementById("test");
e.addEventListener("click", function() {
_this.callHello();
});
}
design.prototype.callHello = function() {
// I expect that this.name will be "designMain"
console.log(this.name)
// will fail if called from the design class eventListener
this.hello();
}
return design;
})();
designMain = (function() {
function designMain() {
this.name = "designMain";
this.init();
}
designMain.prototype.init = function() {
this.extend();
var _this = this;
var e = document.getElementById("test2");
e.addEventListener("click", function() {
_this.callHello();
});
}
designMain.prototype.extend = function() {
var old = new design();
// save reference to original methods
this._designMain = Object.create(old);
for (var name in this._designMain) {
if (!this[name]) {
this[name] = this._designMain[name]
}
}
}
designMain.prototype.hello = function() {
alert("Hello " + this.name);
}
return designMain;
})();
var t = new designMain();
Using ES6 - it works as expected (see fiddle)
class design {
constructor() {
this.name = "design";
var _this = this;
var e = document.getElementById("test");
e.addEventListener("click", function() {
_this.callHello();
});
};
callHello() {
// should be "designMain"
console.log(this.name)
this.hello();
}
get name() {
return this._name;
};
set name(name) {
this._name = name;
};
}
class designMain extends design {
constructor() {
super();
this.name = "designMain";
var _this = this;
var e = document.getElementById("test2");
e.addEventListener("click", function() {
_this.callHello();
});
};
hello() {
alert("Hello " + this.name);
}
}
t = new designMain();