requireJS:移植C ++类,不想两次声明类名

时间:2012-09-06 07:51:24

标签: javascript c++ requirejs

我正在将一个C ++项目移植到Javascript。我想保持面向对象的设计,所以我决定使用requireJS将移植的类组织为模块。 我像这样模拟继承:

define(
[
],

function()
{
    'use strict';

    function Base( arguments )
    {
    }

    function Inherited( arguments )
    {
        Base.call( this, arguments );
    }

    Inherited.prototype = Object.create( Base.prototype );

    return {
                Inherited   : Inherited
            };
});

假设我将此模块保存到文件'inherited.js'并在另一个模块中需要它:

define(
[
    'inherited'
],

function( Inherited )
{
    'use strict';

    function Whatever( arguments )
    {
        var inherited = new Inherited.Inherited( arguments );
    }

    return {
                Whatever    : Whatever,
            };
});

现在困扰我的是,我必须在创建对象时两次声明类名,一次作为模块名称,一次作为函数/类的名称。

相反,我希望能够致电:

var inherited = new Inherited( arguments );

我可以通过在'inherited.js'中返回一个匿名函数来实现这一点,但是我再也无法定义继承依赖。

我意识到模块背后的想法是防止全局命名空间的污染 - 请记住,上面发布的代码仅在我的库中使用,该库在用于实际应用程序之前包装在单个模块中。

所以要实例化函数/ class Inheritated 我必须输入 Library.Inherited.Inherited 但我更喜欢 Library.Inherited

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

只需返回Inherited constructor function:

define(function () {
  function Inherited() {
  }

  Inherited.prototype = {
  };

  return Inherited;
});

模块导出值可以是可返回类型。