javascript - 使用 Google Closure 的继承

标签 javascript inheritance google-closure

我有一个名为“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 ,如果我将 baseScreen 加载为

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 的行上抛出错误至 document.body奇怪的是console.log(this)在第 4 行打印 window对象而不是 baseScreenregisterScreen对象。

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

最佳答案

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

goog.base(this);

它做完全相同的事情。

有关 goog.base 的注释,来自文档:

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.

另见:

关于javascript - 使用 Google Closure 的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11189542/

相关文章:

javascript - 在 ColdFusion 中调用函数时出现 "object expected"JavaScript 错误

javascript - 保留字 JavaScript "this"

sql-server - NHibernate 加入子类

python - 子类化 Python 类以继承父类(super class)的属性

javascript - Internet Explorer 的回退 AJAX 文件上传

javascript - 将 google 脚本对象传递给 html 模板

Javascript:如何覆盖整个区域?

c++ - 在 C++ 中将派生类对象分配和访问到基类 "pointer to pointer"对象

javascript - 如何使用 google-closure 使图形元素可拖动?

google-closure-compiler - Google 关闭变量 window/event/console/... 是未声明的错误