使用谷歌闭包进行继承

Inheritance using Google Closure

本文关键字:继承 闭包 谷歌      更新时间:2023-09-26

我有一个名为'baseScreen'的基类,如下所示:

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');
};

onLoad中,如果我加载基本屏幕作为

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

它工作正常。

然后我派生出一个名为 registerScreen 的屏幕,如下所示:

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); 

当我尝试加载 registerScreen 的对象时,它会在我尝试将this.background附加到第 4 行中document.body和奇怪的console.log(this)的行上抛出错误window打印对象而不是baseScreenregisterScreen对象。

我的代码有什么问题?我是否需要重写加载,在我的派生类中调整大小?(试过这个,但失败了)或任何其他问题?

或者,您也可以将@felix-kling提到的调用替换为:

goog.base(this);

它做完全相同的事情。

关于goog.base的一个注释,来自文档:

如果这是从构造函数调用的,则这将调用带有参数 1-N 的超类构造函数。如果从原型方法调用此方法,则必须将方法的名称作为第二个参数传递给此函数。否则,将出现运行时错误。

另请参阅:

  • http://docs.closure-library.googlecode.com/git/closure_goog_base.js.html
  • http://bolinfest.com/essays/googbase.html)

您必须调用当前registerScreen实例baseScreen

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

否则,你的函数调用等价于 digient.casino.ui.baseScreen() ,因此this引用全局对象window