New Features of JavaScript in Visual Studio 2012: Prototype

Introduction

In my previous article I explained one of the "New Feature of JavaScript in Visual Studio 2012 i.e. Strict Mode". In today's article you will learn about one more new feature of Java Script in Visual Studio 2012, Prototype and Prototype Inheritance.

In JavaScript, prototype is a property of functions and of objects that are created by constructor functions. The prototype of a function is an Object, it's main use is when a function is used as a constructor.

Step 1

First of all add a JavaScript page to your Windows or Web Application. This can be done by right-clicking on your application and then "Add New Item".

prototype1.jpg

Now in the New Item list select the JavaScript Style Sheet.

prototype2.jpg

Step 2

Now in the Style Sheet we will first create a Constructor named "Vehicle Constructor".

function Vehicle(wheels, engine)

{

    this.wheels = wheels;

    this.engine = engine;

}

Here the prototype of the Vehicle function is the prototype of any object instantiated with the Vehicle constructor.

Step 3

Now we will use the Prototype Property to add properties and methods to the Object.

var testVehicle = new Vehicle(2, false);

Vehicle.prototype.color = "red";

var testColor = testVehicle.color;

Now the value of testcolor is Red

Step 4

You can even add properties and methods to predefined Objects. Like here we will define a Trim method on the String Prototype Object and all the Strings in your script will inherit the method.

String.prototype.trim = function ()

{

    return this.replace(/(^\s*)|(\s*$)/g, "");

}

var s = "    leading and trailing spaces    ";

window.alert(s + " (" + s.length + ")");

This code will display the output with spaces and will count it as well. So it will take nearly 35 spaces.

But the following code will trim the blank spaces and will provide the output without taking the spaces.

String.prototype.trim = function ()

{

    return this.replace(/(^\s*)|(\s*$)/g, "");

}

s = s.trim();

window.alert(s + " (" + s.length + ")");

It's output will take only 27 spaces.

Step 5

The Prototype Object can also be used to derive one object from another.

var Bicycle = Object.create(Object.getPrototypeOf(Vehicle),

{

"pedals": { value: true }

});

The Bicycle object thus has the Properties "wheels", "engine", "color" and "pedals" and it's Prototype is "Vehicle.prototype".