将继承与模块模式相结合

17 javascript inheritance design-patterns module

我喜欢返回构造函数的模块模式,如下所述:http: //elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/

但是我不确定如何从使用此模式实现的对象继承.假设我实现了一个父对象...

namespace('MINE');  

MINE.parent = (function() { 
    // private funcs and vars here

    // Public API - constructor
    var Parent = function (coords) {
       // ...do constructor stuff here
    };

    // Public API - prototype
    Parent.prototype = {
       constructor: Parent,
       func1:  function ()    { ... },
       func2:  function ()    { ... }
    }

    return Parent;
 }());
Run Code Online (Sandbox Code Playgroud)

我如何定义一个子对象,它也使用继承的模块模式,parent例如,我可以有选择地覆盖func2

Ray*_*nos 18

MINE.child = (function () {

  var Child = function (coords) {
    Parent.call(this, arguments);    
  }

  Child.prototype = Object.create(Parent.prototype);

  Child.prototype.constructor = Child;
  Child.prototype.func2 = function () { ... };

  return Child;

}());
Run Code Online (Sandbox Code Playgroud)

  • @juminoz我知道做私有实例变量的唯一不可怕的hacky方法是在构造函数中定义它们,并使用this.method =定义在构造函数中依赖它们的所有方法.不幸的是,我非常不喜欢这种做法,因为它为每个实例创建一个新的函数对象,而不是重用原型上的那个.由于这个原因,我倾向于避免使用私有实例变量. (2认同)