business company

advice

Essay




Diploma




Dissertation

How do I create an abstract base class in JavaScript?

Question is quite old, but I created some possible solution how to create abstract "class" and block creation of object that type.

//our Abstract class var Animal=function(){ this.name="Animal"; this.fullname=this.name; //check if we have abstract paramater in prototype if (Object.getPrototypeOf(this).hasOwnProperty("abstract")){ throw new Error("Can't instantiate abstract class!"); } }; //very important - Animal prototype has property abstract Animal.prototype.abstract=true; Animal.prototype.hello=function(){ console.log("Hello from "+this.name); }; Animal.prototype.fullHello=function(){ console.log("Hello from "+this.fullname); }; //first inheritans var Cat=function(){ Animal.call(this);//run constructor of animal this.name="Cat"; this.fullname=this.fullname+" - "+this.name; }; Cat.prototype=Object.create(Animal.prototype); //second inheritans var Tiger=function(){ Cat.call(this);//run constructor of animal this.name="Tiger"; this.fullname=this.fullname+" - "+this.name; }; Tiger.prototype=Object.create(Cat.prototype); //cat can be used console.log("WE CREATE CAT:"); var cat=new Cat(); cat.hello(); cat.fullHello(); //tiger can be used console.log("WE CREATE TIGER:"); var tiger=new Tiger(); tiger.hello(); tiger.fullHello(); console.log("WE CREATE ANIMAL ( IT IS ABSTRACT ):"); //animal is abstract, cannot be used - see error in console var animal=new Animal(); animal=animal.fullHello();

As You can see last object give us error, it is because Animal in prototype has

The Best Essay Writing Service - EssayBox.org

property abstract. To be sure it is Animal not something which has Animal.prototype in prototype chain I do:

Object.getPrototypeOf(this).hasOwnProperty("abstract")

So I check that my closest prototype object has abstract property, only object created directly from Animal prototype will have this condition on true. Function hasOwnProperty checks only properties of current object not his prototypes, so this gives us 100% sure that property is declared here not in prototype chain.

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain. More about it:

In my proposition we not have to change constructor every time after Object.create like it is in current best answer by @Jordão.

Solution also enables to create many abstract classes in hierarchy, we need only to create abstract property in prototype.


Category: Abstract

Similar articles: