I have the following situation, in which I extend a parent class and override behavior. However the overridden behavior is not called.
// parent scope definition
(function ($) {
$.extend(true, window, {
Demo: {
Parent: Parent
}
});
function Parent() {
function A() {
//do something
}
function B() {
//do something else
A();
}
// public api
$.extend(this,{ "A":A, "B":B });
}
})(jQuery);
// child scope definition
(function ($,parent) {
$.extend(true, window, {
Demo: {
Child: Child
}
});
function Child() {
// inherit all from parent
parent.apply(child,arguments);
this.A = function () {
// override parent behavior
}
this.B();
}
})(jQuery,Parent);
//...somewhere else, in another scope call: var kid = new Child();
<html>
<script>
var kid = new Child();
</script>
</html>
When creating a new Child object, B will be called, with "this" pointing to the Child context. However, the context of A will not the Child, but the global (window) context. The overridden behavior for A will not be called either.
I have to use the module pattern (no prototypical inheritance) and also override "superclass" behavior.
Could someone please let me know how I can "preserve" the context, in order to make sure the overridden behavior is called.
Thank you in advance, Andrei
edit #1: I must use modules (and hopefully do as little change to the "Parent" as possible when overriding behavior)
edit #2: For more clarity, thanks to the answers provided below, I must use the "revealing module pattern" for the Parent
module/object and extend/override its behavior in Child
.
edit #3: It seems the question title and problem are different and may be misleading: the handled and answered problems which are the real core issue are regarding javascript overriding in the context of the (revealing) module patter (as indicated in one of the answers). The scope change (which does occur) has been mistakenly considered as the real problem. I am removing its mention form the title. The correction is done so that others may benefit from answers below. There is a scope change, but that is probably normal in the present code design and in my calling scenario. Disregard this aspect (context) in this question.