Javascript Abstract Class with Object create

This is my abstract class:

var Animal = function(){
    this.name = ''
    this.legs = 0;
    throw new Error("cannot instantiate abstract class");
}
Animal.prototype.walk = function(){ console.log(this.name+ " walked")};

      

Creating a new concrete class:

var Dog = function(){} ;

      

Now I want the concrete Dog class to inherit from the abstract Animal class. I tried both ways below. Which one is the standard ?:

Dog.prototype = Object.create(Animal.prototype)

      

OR

Dog.prototype = Animal.prototype

      

I also tried var Dog = Object.create(Animal)

which gave me the error.

+3


source to share


1 answer


Inside the class, Animal

you can do a check if

to see if the current one constructor

Animal

and throws an error if there is one. When you call the parent constructor internally Dog

and inherit from the prototype, you also need to set its pointer to the constructor Dog

.



var Animal = function() {
  this.name = ''
  this.legs = 0;
  if (this.constructor == Animal) {
    throw new Error("cannot instantiate abstract class");
  }
}
Animal.prototype.walk = function() {
  console.log(this.name + " walked")
};

function Dog() {
  Animal.call(this);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var inst = new Dog;
inst.name = 'lorem';
inst.walk()
      

Run codeHide result


0


source







All Articles