Design patterns Prototype Pattern Prototype Pattern (JavaScript)


Example

In the classical languages like Java, C# or C++ we start by creating a class and then we can create new objects from the class or we can extend the class.

In JavaScript first we create an object, then we can augment the object or create new objects from it. So i think, JavaScript demonstrates actual prototype than the classical language.

Example :

var myApp = myApp || {};

myApp.Customer = function (){
    this.create = function () {
        return "customer added";
    }
};

myApp.Customer.prototype = {
    read: function (id) {
        return "this is the customer with id = " + id;
    },
    update: function () {
        return "customer updated";
    },
    remove: function () {
        return "customer removed";
    }
};

Here, we create an object named Customer, and then without creating new object we extended the existing Customer object using prototype keyword. This technique is known as Prototype Pattern.