简体   繁体   中英

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?

Alternatively, you could also replace the call mentioned by @felix-kling with:

goog.base(this);

which does the exact same thing.

One note about goog.base, from the docs:

If this is called from a constructor, then this calls the superclass constructor with arguments 1-N. If this is called from a prototype method, then you must pass the name of the method as the second argument to this function. If you do not, you will get a runtime error.

see also:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM