JS module pattern override function
Asked Answered
B

1

6

I have following pattern

BASE = function () {
    var that = {};
    var number = 10;

    that.showNumber = function(){
        that.alertNumber();
    }

    that.alertNumber = function () {
        alert(number);
    };    
    return that;
};

CHILD = function () {
    var that = Object.create(BASE());
    var secondNumber = 20;

    // Override base function
    that.alertNumber = function () {
        alert(secondNumber);
    };
    return that;
};

var ch = CHILD();
ch.showNumber();

Can you tell me how can I adjust my module pattern inspired by Douglas CrockFord to fully override alerNumber function? So far showNumber function displays 10 instead of 20.

Thank you all in advanced

JSFiddle with code is here

Bevatron answered 31/5, 2013 at 14:22 Comment(3)
Why not simply use prototype ? This would make it simple.Amphibolite
Why not write var that = new BASE(); ?Confabulate
This pattern allows multiple inheritanceMarilou
M
5

You could change

that.showNumber = function(){
    that.alertNumber();
}

to

that.showNumber = function(){
    this.alertNumber();
}

But I'm not sure I see why you don't simply use the prototype-base inheritance model.

Metamerism answered 31/5, 2013 at 14:26 Comment(5)
That's the thing that I do not fully understand. Why this.alertNumber() in base is referenced to that in Base class?Marilou
This pattern you use sets a that variable in the closure to get sure the function showNumber is using the instance defined in the constructor, thus making most advanced inheritance schemes not working (for example a superclass function calling another function and letting it be overridden).Amphibolite
OK so if I get it well, when I want to be able to override parent function I have to use different pattern? I am sorry for such a noobish questions, but I have experience only with Java where inheritance is totally different.Marilou
Well, this pattern lets you override parent function, it just doesn't let you, if you're using that, call the child function from the parent. I'd suggest to use the standard pattern (see the link in my answer) as long as you aren't used to JavaScript (then you'll maybe use your own, which isn't so rare). And don't use "classes" when you don't need them. If your JS looks like Java, you're doing it wrong. You should have many functions and callbacks and not a lot of classes, even in a big application.Amphibolite
What I did not understand from your link how can I "hide" private variables and use them in public functions see this fiddleMarilou

© 2022 - 2024 — McMap. All rights reserved.