使用Google Closure Library剖析正确的继承/子类实现

时间:2015-01-13 18:32:45

标签: javascript inheritance google-closure limejs

我开始使用Google的Closure Library(以及Lime.js),我正在尝试创建一个非常基本的场景,其中包含Lime的自定义子类的一些实例的.js' lime.Layer类。

据我所知(正如我在各种示例和Google自己的文档中所读到的那样),您的子类中需要有7个项目才能正确地从其中继承超级,并可供其他课程使用:

  • goog.provide(" name.of.subclass&#34)
  • goog.require(" name.of.superclass&#34)
  • 在构造函数@constructor
  • 上面的注释中
  • 在构造函数@extends name.of.superclass
  • 上面的注释中
  • 在构造函数内部,调用name.of.superclass.call(this)
  • 在构造函数之后,goog.inherits(name.of.subclass,name.of.superclass)
  • 最后,使用goog.exportSymbol导出构造函数(' name.of.subclass',name.of.subclass)

我的项目结构很简单。 "的index.html"与名为" js"的文件夹一起位于主要级别,该文件夹包含我的所有自定义JavaScript文件。我已经运行了其他更简单的测试,确认Closure和Lime正在加载并正确初始化。我只想尝试下一步进入更多OO风格的模式。我的代码和我遇到的错误都在下面。


的index.html

<!DOCTYPE html>
<html>
    <head>
        <title>LimeTest</title>
        <script type="text/javascript" src="../closure/closure/goog/base.js"></script>
        <script type="text/javascript" src="js/limetest.js"></script>
    </head?
    <body onload="limetest.start()"></body>
</html>

JS / limetest.js

// Expose class
goog.provide('limetest');

// Import dependencies
goog.require('lime.Director');
goog.require('lime.Scene');
goog.require('lime.Layer');

// Import custom subclass of lime.Layer
goog.require('stupid.thing');

// Main Start function
limetest.start = function ()
{
    // setup Lime.js scene
    var director = new lime.Director(document.body, 1024, 768);
    var scene = new lime.Scene();
    var mainLayer = new lime.Layer().setPosition(512, 384);

    // instantiate subclass
    var something = new stupid.thing();

    // assemble scene
    scene.appendChild(mainLayer);
    mainLayer.appendChild(something);
    director.makeMobileWebAppCapable();
    director.replaceScene(scene);
}

// Export start method
goog.exportSymbol('limetest.start', limetest.start);

JS / thing.js

goog.provide('stupid.thing');

goog.require('lime');
goog.require('lime.Layer');

/*
*   @constructor
*   @extends lime.Layer
 */
stupid.thing = function ()
{
    lime.Layer.call(this);
};
goog.inherits(stupid.thing, lime.Layer);

goog.export('stupid.thing', stupid.thing);

我在Chrome中遇到的错误是:

base.js:     634   goog.require could not find: stupid.thing
base.js:     634   goog.logToConsole_
base.js:     675   goog.require
limetest.js: 10    (anonymous function)

base.js:     677   Uncaught Error: goog.require could not find: stupid.thing
base.js:     677   goog.require
limetest.js: 10    (anonymous function)

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

基本上,您有两种解决依赖关系的选择: 1)手动加载依赖脚本 2)加载deps.js文件,该文件提供依赖项的路径

通常,&#34; deps.js&#34;生成了(石灰是否为你做了这件事,我不熟悉它)?

作为旁注,你可能想尝试goog.defineClass,它从类定义中删除了一些样板文件(@ constructor,@ extends和goog.inherits是隐含的)。