JavaScript Prototype Design Pattern

Petr Kostelanský | 12 October 2017
This article show a few examples about prototype pattern especially base class creation, inheritance and how access base class.

Class definition

There is a simple classs definition for prototype design pattern:

var Animal = function (legs, weight, speed) {
    this.legs = legs;
    this.weight = weight;
    this.speed = speed;
};

Animal.prototype.maxMobility = function () {
    return "Max mobility " + (this.weight * this.speed);
};

var dog = new Animal(4,30,40);
alert(dog.maxMobility());

Class inheritance

To create inheritance we have to use Object.create():

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

Example:

var Animal = function (legs, weight, speed) {
    this.legs = legs;
    this.weight = weight;
    this.speed = speed;
};
Animal.prototype.maxMobility = function () {
    return "Max mobility " + (this.weight * this.speed);
};

var Dog = function (weight, speed) {
    Animal.call(this, 4, weight, speed);
};
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var dog = new Dog(10, 20);
alert(dog.maxMobility());

Base class access

To access base class we have to use call() method.

There is an example how to access base class constructor and base class method maxMobility():

var Animal = function (legs, weight, speed) {
    this.legs = legs;
    this.weight = weight;
    this.speed = speed;
};
Animal.prototype.maxMobility = function () {
    return "Max mobility " + (this.weight * this.speed);
};

var Dog = function (weight, speed) {
    Animal.call(this, 4, weight, speed);
};
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.maxMobility = function() {
	return "Dog: " + Animal.prototype.maxMobility.call(this);
};

var dog = new Dog(10, 20);
alert(dog.maxMobility());
Loading ads...