我有一个名为“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
对象而不是 baseScreen
或 registerScreen
对象。
我的代码有什么问题?我是否需要在我的派生类中覆盖加载、调整大小? (尝试过,但失败)或任何其他问题?
最佳答案
或者,您也可以将@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/