Click here to Skip to main content
15,921,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create class in JavaScript?
Posted

 
Share this answer
 
Comments
Rahul Rajat Singh 26-Jun-12 6:41am    
+5 for the links.
uspatel 26-Jun-12 7:41am    
Thanks Rajat......
Espen Harlinn 26-Jun-12 7:22am    
5'ed!
 
Share this answer
 
Comments
Rahul Rajat Singh 26-Jun-12 6:41am    
+5 for the links.
Prasad_Kulkarni 26-Jun-12 7:22am    
Thank you Rahul!
Espen Harlinn 26-Jun-12 7:22am    
Nice set of good links :-D
Prasad_Kulkarni 26-Jun-12 7:23am    
:) Thank you Espen.
JavaScript
function Person(fn,ln)
{
    this.FirstName = fn;
    this.LastName = ln;
    if(typeof this.GetFullName != "function"){
        Person.prototype.GetFullName = function()
        {
            return this.FirstName + ' ' + this.LastName;
        }
    }
}
var p = new Person('jon','smith');
alert(p.GetFullName()); 
 
Share this answer
 
Hi,

Consider you want to create a javascript class for Rect.

JavaScript
function Rect(top,left,width,height){
	this.top = top;
	this.left = left;
	this.width = width;
	this.height = height;
}

Rect.prototype.getTop = function(){
	return this.top;
}

Rect.prototype.getLeft = function(){
	return this.left;
}

Rect.prototype.getBottom = function(){
	return (this.top + this.height);
}

Rect.prototype.getRight = function(){
	return (this.left + this.width);
}

Rect.prototype.getWidth = function(){
	return this.width;
}

Rect.prototype.getHeight = function(){
	return this.height;
}



Now, If I want to use this class, I can do that as following:

var rc = new Rect(0,0,100,100);
var rcTop = rc.getTop();
var rcLeft = rc.getLeft();
....
....
....


Hope, this will satisfy your need.

Thanks
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900