65.9K
CodeProject is changing. Read more.
Home

Prototype In Javascript - Basic

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.87/5 (9 votes)

May 2, 2014

CPOL

1 min read

viewsIcon

18735

downloadIcon

192

The prototype property allows you to add properties and methods to an object.

What is Prototype?

The prototype property allows you to add properties and methods to an object.

  • Prototype is a property of function object.
  • Only function objects can have prototype property.

Function

  • Are objects.
  • Returns value.
  • Can return objects, including other functions.
  • They have properties.
  • They have methods.
  • Can be copied, delete, augmented.

for example:

var foo = function() { };
Console.log(foo.prototype); // Output: Object {}

What is Object?

Anything created with the new keyword is an object.

for example:

new String("hi");
new Object();
new Array();
Person = function(name) { 
    this.name = name
}
Me = new Person("Imdadhusen");

Object will make your code much more cleaner and easy to maintain, It represents the context of your entire function or code block.

var timer = { start: 1000, stop: 2000 }; 

When you revisit the code after sometime, it will be bit difficult to remember or map why 2000 is used. But instead, if maintain an object and say 'stop', then you can be able to identify its significance.

Good Things Of Prototype

  • Encourage modularity and re-usability
  • Provide a consistent way to do (different) things
  • Keep code to a minimum
  • Make complexity easy

Augmenting Prototype

Adding constructor, properties and methods to prototype object.

// instantiates an object of foo
var myfoo = new foo(); 
//Access Method of foo
console.log(myfoo.SayHello("Imdad"));  // Output "Hello Imdad!"
//Access Property of foo
console.log(myfoo.Name);  // Output "Imdad!" 
  

Examples of Prototype

  • String
  • Number
  • Date
  • Array
  • Function
    • Using Pure JavaScript
    • Using jQuery

String

The String.prototype property represents the prototype for the String constructor

Example:

//Get File Name with Extension from Full Path
alert("C:\www\scripts\views\Utils.js".getFileName());  //Output: Utils.js
String.prototype.getFileName = function(){
     return this.match(/[^\\/]+\.[^\\/]+$/)[0];
}

alert("imdad{0}".isValidName()); //Output: false
//Username should be minimum 3 char and maximum 15 and it allowed 
//only ( .\-_$@*) special characters.
String.prototype.isValidName = function() {
     var regex = /^[a-zA-Z0-9 .\-_$@*!]{3,15}$/;
     return regex.test(this);
}

alert("imdad@yahoo.com".isValidEmail()); //Output: true
//Checking email is valid or not
String.prototype.isValidEmail = function() {
    var regex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
    return regex.test(this);
}

Number

The Number.prototype property represents the prototype for the Number constructor

Example:

var start = 100;
var end = 200;
var value = 150;
if(value.isInRange(start,end)) //Output: 'Value is in Range'
   alert('Value is in Range');
else
    alert('Value is not in Range');

//Validate number only and within range
Number.prototype.isInRange = function(start,end){
    this.Min = start||100;
    this.Max = end||200;
    return (this.Max >= this.valueOf() && this.Min <= this.valueOf());
}

Date

The Date.prototype property represents the prototype for the Date constructor

Example:

var dt = new Date();
alert(dt.shortDate()); //Output: Fri, 2 May 14
alert(dt.fullDate());  //Output: Friday, 2 May 2014

Date.prototype.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        Date.prototype.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        Date.prototype.fullDay = function() {
            return this.dayNames[this.getDay()];
        };
        Date.prototype.shortDay = function() {
            return this.fullDay().slice(0, 3);
        };

        Date.prototype.fullMonth = function() {
            return this.monthNames[this.getMonth()];
        };
        Date.prototype.shortMonth = function() {
            return this.fullMonth().slice(0, 3);
        };
        Date.prototype.shortYear = function() {
            return this.getFullYear().toString().substr(2,2);
        };

        Date.prototype.shortDate = function() {
            return this.shortDay() +', '+ this.getDate() +' '+ this.shortMonth() +' '+ this.shortYear();
        }

        Date.prototype.fullDate = function() {
            return this.fullDay()  +', '+ this.getDate() +' '+ this.fullMonth() +' '+ this.getFullYear()
        }

Array

The Array.prototype property represents the prototype for the Array constructor

Example:

//Define list of users in Array for remove by index and key/pair value
var users = new Array(
                { 'Country' : 'India', 'Code' : '+91'},
                { 'Country' : 'Afghanistan', 'Code' : '+93'},
                { 'Country' : 'Bhutan', 'Code' : '+975'},
                { 'Country' : 'Brazil', 'Code' : '+55'},
                { 'Country' : 'China', 'Code' : '+86'},
                { 'Country' : 'Egypt', 'Code' : '+20'},
                { 'Country' : 'Greece', 'Code' : '+30'}
            );
users.renderList('#olUsersList'); //Render list of all users with index on order list (olUsersList)

//Remove user by Index (4) start with 0
users.removeByIndex(4);
//Refresh users list
users.renderList('#olUsersList');

//Remove user by Key (Country) and Value (Bhutan)
var key = 'Country';
var val = 'Bhutan';
users.removeByObject(key, val);
//Refresh users list
users.renderList('#olUsersList');

Array.prototype.removeByIndex = function(index) {
            this.splice(index, 1);
            return this;
        }
        Array.prototype.removeByObject = function(key, val) {
            var getUser = this.getObject(key, val);
            if(getUser !== null)
                this.splice(getUser.index, 1);
            return this;
        }
        Array.prototype.getObject = function(key, val) {
            for (var i=0; i < this.length; i++)
            {
                if (this[i][key] == val)
                    return { 'index': i , 'obj' : this[i] };
            }
            return null;
        };
        Array.prototype.renderList = function(ele) {
            $(ele).empty();
            this.forEach(function(item) {
                $(ele).append('<li>'+>('+ item.Code +')');
            });
        }
</li>'+>

Function using jQuery

Using jquery we can extending our function object. Example:
jQuery.fn.extend({
     setScrollbar: function(height) {
          return this.css({'overflow' : 'auto', 'height': height});
     }
});

$(document).ready(function(){
   $('#btnApplyjQueryScroll').click(function(){
       $('#dvScoll_jQuery').setScrollbar(250);
   });
});

Function using pure JavaScript

You can create your own custom control using pure JavaScript. Example:
function myScroll(ele){
    this.element = document.getElementById(ele);
}
myScroll.prototype.setScrollbar = function(height){
    this.element.style.height = height + 'px';
    this.element.style.overflow = 'auto';
}

$(document).ready(function(){
   $('#btnApplyJSScroll').click(function(){
       var t = new myScroll('dvScoll_JS');
       t.setScrollbar(150);
   });
});
I have shown above all the examples are beginner level developer. They will get more clear idea about how prototype works for each datatype. If you would like to know about more please let me know.