Click here to Skip to main content
15,878,970 members
Articles / Web Development / HTML

Prototype In Javascript - Basic

Rate me:
Please Sign up or sign in to vote.
4.87/5 (9 votes)
2 May 2014CPOL1 min read 18.2K   192   16   2
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:

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

What is Object?

Anything created with the new keyword is an object.

for example:

JavaScript
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.

JavaScript
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.

Image 1

JavaScript
// 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:

JavaScript
//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:

JavaScript
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:

JavaScript
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:

JavaScript
//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:
JavaScript
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:
JavaScript
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Infostretch Ahmedabad-Gujarat
India India
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen


AWARDS:

  1. 2nd Best Mobile Article of January 2015
  2. 3rd Best Web Dev Article of May 2014
  3. 2nd Best Asp.Net article of MAY 2011
  4. 1st Best Asp.Net article of SEP 2010


Read More Articles...

Comments and Discussions

 
Questionoutput showing error for below code Pin
Divya78901231-Nov-17 8:06
Divya78901231-Nov-17 8:06 
AnswerRe: output showing error for below code Pin
Sunasara Imdadhusen13-Nov-17 18:40
professionalSunasara Imdadhusen13-Nov-17 18:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.