JavaScript Classes

前端 未结 8 461
心在旅途
心在旅途 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();
    

提交回复
热议问题