JavaScript Extending Class

前端 未结 10 1410

I have a base class:

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

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

That

10条回答
  •  旧时难觅i
    2020-11-30 18:26

    Try this:

    Function.prototype.extends = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    Monkey.extends(Monster);
    function Monkey() {
      Monster.apply(this, arguments); // call super
    }
    

    Edit: I put a quick demo here http://jsbin.com/anekew/1/edit. Note that extends is a reserved word in JS and you may get warnings when linting your code, you can simply name it inherits, that's what I usually do.

    With this helper in place and using an object props as only parameter, inheritance in JS becomes a bit simpler:

    Function.prototype.inherits = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    function Monster(props) {
      this.health = props.health || 100;
    }
    
    Monster.prototype = {
      growl: function() {
        return 'Grrrrr';
      }
    };
    
    Monkey.inherits(Monster);
    function Monkey() {
      Monster.apply(this, arguments);
    }
    
    var monkey = new Monkey({ health: 200 });
    
    console.log(monkey.health); //=> 200
    console.log(monkey.growl()); //=> "Grrrr"
    

提交回复
热议问题