JavaScript Extending Class

前端 未结 10 1406

I have a base class:

function Monster() {
  this.health = 100;
}

Monster.prototype.growl = function() {
  console.log(\"Grr!\");
}

That

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 18:45

    For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

         function AbstractClass() {
          this.superclass_method = function(message) {
              // do something
            };
         }
    
         function Child() {
             AbstractClass.apply(this);
             // Now Child will have superclass_method()
         }
    

    Example on angularjs:

    http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview

    app.service('noisyThing', 
      ['notify',function(notify){
        this._constructor = function() {
          this.scream = function(message) {
              message = message + " by " + this.get_mouth();
              notify(message); 
              console.log(message);
            };
    
          this.get_mouth = function(){
            return 'abstract mouth';
          }
        }
      }])
      .service('cat',
      ['noisyThing', function(noisyThing){
        noisyThing._constructor.apply(this)
        this.meow = function() {
          this.scream('meooooow');
        }
        this.get_mouth = function(){
          return 'fluffy mouth';
        }
      }])
      .service('bird',
      ['noisyThing', function(noisyThing){
        noisyThing._constructor.apply(this)
        this.twit = function() {
          this.scream('fuuuuuuck');
        }
      }])
    

提交回复
热议问题