سؤال

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?

هل كانت مفيدة؟

المحلول

some modification of your code (1 line):

.......
var init = function() {
    console.log('init');
    //customInit.call(this);
    this.customInit.call(this);
},
.....

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top