JavaScript Classes

前端 未结 8 463
心在旅途
心在旅途 2020-12-07 09:21

I understand basic JavaScript pseudo-classes:

function Foo(bar) {
    this._bar = bar;
}

Foo.prototype.getBar = function() {
    return this._bar;
};

var f         


        
相关标签:
8条回答
  • 2020-12-07 10:14

    I was thinking about this particular subject recently and the limitations of the various approaches. The best solution I've been able to come up with is below.

    It seems to solve the problems with inheritance, instantiation and ecapsulation (at least from tests on Google Chrome v.24) although probably at a cost in memory usage.

    function ParentClass(instanceProperty) {
      // private
      var _super = Object.create(null),
          privateProperty = "private " + instanceProperty;
      // public
      var api = Object.create(_super);
      api.constructor = this.constructor;
      api.publicMethod = function() {
         console.log( "publicMethod on ParentClass" );
         console.log( privateProperty );
      };
      api.publicMethod2 = function() {
         console.log( "publicMethod2 on ParentClass" );
         console.log( privateProperty );
      };
      return api;
    }
    
    function SubClass(instanceProperty) {
        // private
        var _super = ParentClass.call( this, instanceProperty ),
            privateProperty = "private sub " + instanceProperty;
        // public
        var api = Object.create(_super);
        api.constructor = this.constructor;
        api.publicMethod = function() {
           _super.publicMethod.call(this); // call method on ParentClass
            console.log( "publicMethod on SubClass" );
            console.log( privateProperty );
        }
        return api;
    }
    
    var par1 = new ParentClass(0),
        par2 = new ParentClass(1),
        sub1 = new SubClass(2),
        sub2 = new SubClass(3);
    
    par1.publicMethod();
    par2.publicMethod();
    sub1.publicMethod();
    sub2.publicMethod();
    par1.publicMethod2();
    par2.publicMethod2();
    sub1.publicMethod2();
    sub2.publicMethod2();
    
    0 讨论(0)
  • 2020-12-07 10:15

    I think what you're looking for is the "Revealing Prototype Pattern".

    Dan Wahlin has a great blog post: http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx

    and even better Pluralsight course on this and other related JavaScript structures: http://pluralsight.com/training/courses/TableOfContents?courseName=structuring-javascript&highlight=dan-wahlin_structuring-javascript-module1!dan-wahlin_structuring-javascript-module2!dan-wahlin_structuring-javascript-module5!dan-wahlin_structuring-javascript-module4!dan-wahlin_structuring-javascript-module3#structuring-javascript-module1

    0 讨论(0)
提交回复
热议问题