2

I'm currently struggling with some concepts and syntax for the Revealing Prototype Pattern in Javascript. Could you guys help me understand it?

What I am trying to achieve: call an overridden method from another method of the base class.

How I did it:

  1. Base class:

    var Base = function() {
        //...
    };
    Base.prototype = function() {
        var init = function() {
            console.log('init');
            customInit.call(this);
        },
        customInit = function() {
            console.log('custom init source');
        };
    
        return {
            init: init,
            customInit: customInit
        };
    } ();
    
  2. Extended class:

    var Extended = function () {
        //...
    };
    Extended.prototype = new Base();
    Extended.prototype.customInit = function () {
        console.log('custom init extended');
    };
    
  3. Call to extended class:

    window.addEventListener('load', function (){
        var myObject = new Extended();
        myObject.init();
        myObject.customInit();
    });
    

The call to customInit from outside of the class executes the overriden version of the method (what I want), while the call from within the class still calls the "base" version of the method (not what I want).

Is this normal? Is there any workaround to achieve this?

Yosko
  • 329
  • 1
  • 4
  • 15

2 Answers2

2

some modification of your code (1 line):

.......
var init = function() {
    console.log('init');
    //customInit.call(this);
    this.customInit.call(this);
},
.....
Vlad Nikitin
  • 1,929
  • 15
  • 17
1

You can call a parent function in child with Parents.prototype. some function.call(this, param1, param2)

For more info you can check out this answer:https://stackoverflow.com/a/16063711/1641941

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
  • Sounds more like the opposite of what I wanted to achieve. Still, super useful information (and link). Thanks a lot. – Yosko Feb 07 '14 at 10:41