使用谷歌闭包进行继承
Inheritance using 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
中,如果我加载基本屏幕作为
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
打印对象而不是baseScreen
或registerScreen
对象。
我的代码有什么问题?我是否需要重写加载,在我的派生类中调整大小?(试过这个,但失败了)或任何其他问题?
或者,您也可以将@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
。
相关文章:
- 在underscorejs模板中使用闭包
- setTimeout可以与闭包内的函数一起使用吗
- 附加到原型属性的Do函数没有闭包
- 使用闭包共享构造函数参数
- 使用Google闭包编译器包含一个Ecmascript 6类
- 从js引擎的角度来看闭包和构造函数是如何工作的
- for循环中的JavaScript闭包
- Javascript闭包-如何防止内存泄漏
- 如何使用继承创建类似谷歌闭包的结构
- 使用谷歌闭包进行继承
- 为什么允许通过原型继承访问另一个闭包范围内的私有变量
- 使用Google闭包库的正确继承/子类实现剖析
- 在javascript中,当原型继承比闭包更适合创建对象时
- 谷歌闭包编译器:如何在使用工厂时进行继承
- 获得'未定义'使用闭包工具继承时出现属性错误
- 如何在承诺链中继承数据而不创建闭包
- 谷歌闭包库继承属性
- 如何在大项目的闭包模板中没有继承
- 使用google闭包的多级继承
- 为什么“;代理“;继承停止处理闭包