0

问题:

过去两周我一直在研究的一个看似简单的问题(请放轻松,因为我是新手!):

在使用 Require.js 和 Revealing Module Pattern 时,如何巧妙地在 JavaScript 中实现继承?


例子:

这是一个示例模块,它是某种类型的“ Component”的基类:

define('Component', [], function () {
   "use strict";

   var _privateVar = 10;
   var _doPrivateThings = function () {  /* do stuff */ };    
   var init = function () { /* do stuff */ };
   var update = function () {  /* do stuff */ };

   return {
      init : init,
      update : update
   };

});

接下来我想实现CakeComponent应该继承所有内容Component并允许我编辑/添加方法和属性:

define('CakeComponent', ['Component'], function (Component) {
   "use strict";
   
   // Setup inheritance
   var CakeComponent = function() {}
   CakeComponent.prototype = new Component();

   // Add/edit methods/properties
   CakeComponent.prototype.newMethod = function () { /* do stuff */ };

   return {
      init : CakeComponent.init,
      update : CakeComponent.update,
      newMethod : CakeComponent.newMethod
   };

});

首先,我不确定这是否完全有意义,但其次,我的 CakeComponent 感觉有点恶心,因为现在我CakeComponent到处都有这种冗余,我不得不“重新揭示” initandupdate方法。

我真的更喜欢这样的东西(我意识到这没有意义,它实际上只是伪代码):

define('CakeComponent', ['Component'], function (Component) {
   "use strict";

   this.extends(Component);
   var newMethod = function () { /* do stuff */ };

   return {
      newMethod : newMethod
   };

});

任何提示或建议将不胜感激。谢谢。


更多详细信息

  • 也许我应该总是在define包装器中创建一个类对象?我见过人们这样做,但在我遇到这个问题之前似乎没有必要。
  • 函数对象上的.call()方法在这种情况下是否有用?例如使用Component.call()
  • @Bergi 请参见下文:

define([], function () {
    "use strict";

    var Component = function () {

        var _privateVar = 10;
        var _doPrivateThings = function () {  /* do stuff */ };
        this.init = function () { /* do stuff */ };
        this.update = function () {  /* do stuff */ };

    };

    return Component;

});
4

1 回答 1

0

我以前见过这种模型,称为通用模块定义:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['Component'], factory);
    } else {
        root.CakeComponent = factory(root.Component);
    }
}(this, function (Component) {
    return {
        newMethod: function(){ /* do stuff */ }
    };
}));

你可以试试这个,这不是“真正的”继承——如果它不起作用——根据环境,你可能还需要传递基本函数,这很遗憾:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['Component'], factory);
    } else {
        root.CakeComponent = factory(root.Component);
    }
}(this, function (Component) {
    return {
        init: Component.init,
        update: Component.update,
        newMethod: function(){ /* do stuff */ }
    };
}));

您可以在这篇关于通用模块定义的精彩文章中阅读有关此主题的更多信息

于 2015-04-24T07:32:57.663 回答