Combining inheritance with the module pattern

前端 未结 2 1444
梦毁少年i
梦毁少年i 2020-12-07 23:46

I like the module pattern that returns constructors as described in: http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/

However I am not

相关标签:
2条回答
  • 2020-12-08 00:14

    I find the solution from this blog (http://metaduck.com/08-module-pattern-inheritance.html) cleaner. For example:

    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 + "'s father");
    
        // Override
        exportObj.func2 = function () {
            alert("Child func2. Name: " + name);
        }
    
        // Export public interface
        return exportObj;
    }
    

    An example can be run here: http://jsfiddle.net/wt4wcuLc/

    0 讨论(0)
  • 2020-12-08 00:19
    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;
    
    }());
    
    0 讨论(0)
提交回复
热议问题