Search code examples
javascriptinheritancegoogle-closure

Inheritance using Google Closure


I have a base class named 'baseScreen' as follows:

digient.casino.ui.baseScreen = function() {
    goog.debug.Logger.getLogger('demo').info('baseScreen');
    this.background                             =   goog.dom.createDom('div', {'class': 'backgroundHolder'}, '');
    console.log(this);
}

digient.casino.ui.baseScreen.background         =   null;

digient.casino.ui.baseScreen.prototype.load     =   function() {
    var self                                    =   this;
    goog.debug.Logger.getLogger('demo').info('baseScreen : load');
    goog.dom.appendChild(document.body, this.background);
    <!-- screen setup code goes here -->
};

digient.casino.ui.baseScreen.prototype.resize  =   function(newSize) {
    goog.debug.Logger.getLogger('demo').info('baseScreen : resize');
};

in onLoad, if I load baseScreen as

var sc = new digient.casino.ui.baseScreen();
sc.load();

its working fine.

Then I derive a screen named registerScreen as follows:

digient.casino.ui.registerScreen = function() {                                                     
    goog.debug.Logger.getLogger('demo').info('registerScreen');                                     
    digient.casino.ui.baseScreen.call();
};                                                                                                  
goog.inherits(digient.casino.ui.registerScreen, digient.casino.ui.baseScreen); 

When I try to load object of registerScreen, its throwing an error on the line where I try to append this.background to document.body and weirdly console.log(this) in line 4 prints window object instead of baseScreen or registerScreen object.

Whats wrong with my code? Do I need to override load, resize in my derived class? (tried this, but failure) or any other problem?


Solution

  • You have to call baseScreen will the current registerScreen instance:

    digient.casino.ui.baseScreen.call(this);
    

    Otherwise, your function call is equivalent to digient.casino.ui.baseScreen(), hence this refers to the global object window.