Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Creating Custom Class in JavaScript and adding methods, properties.

3.17/5 (24 votes)
29 Aug 2006 1  
This is a brief example of creating custom object in JavaScript.

Introduction

This is a brief example of creating custom object in JavaScript.

Creating Class

For creating class in javascript first we have to create the function whose name should be same as class. This function is called as constructer.

For example I want to create the class Named MyClass so function name should be MyClass

JavaScript
function MyClass()
{ 
    //This function is same as a constructer 
    alert("New Object Created"); 
}

We can also add the argumnets in this function.

Now I am making object of MyClass

JavaScript
//Creating Object 
var MyObject = new MyClass (); 

Adding new method and property in "MyClass"

JavaScript
NewObject.prototype = 
{ 
    //Adding Method named "MyMethod" 
    MyMethod: function(){alert("My Method");} , 
 
    //Adding property named "MyProperty" 
    MyProperty: "My Property" 
}

Calling method and assigning value to property

JavaScript
//Calling Method 
MyObject.MyMethod(); 

//Assigning Property 
MyObject.MyProperty = "My Property Value changed"; 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here