Объединение наследования с шаблоном модуля - программирование
Подтвердить что ты не робот

Объединение наследования с шаблоном модуля

Мне нравится шаблон модуля, который возвращает конструкторы, как описано в: 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;
 }());

Как определить дочерний объект, который также использует шаблон модуля, который наследует от parent таким образом, что я могу выборочно переопределить, например, func2?

4b9b3361

Ответ 1

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;

}());

Ответ 2

Я нашел решение из этого блога (http://metaduck.com/08-module-pattern-inheritance.html). Например:

function Parent(name) {
    // Private variables here
    var myName;

    // Constructor
    myName = name;

    // Public interface
    return {
        func1: function () {alert("Parent func1. Name: " + myName); },
        func2: function () {alert("Parent func2. Name: " + myName); }
    }
}

function Child(name) {
    // Private variables here
    var myName,
        exportObj;

    // Constructor
    // Inherit
    exportObj = Parent(name + " father");

    // Override
    exportObj.func2 = function () {
        alert("Child func2. Name: " + name);
    }

    // Export public interface
    return exportObj;
}

Пример можно запустить здесь: http://jsfiddle.net/wt4wcuLc/