65.9K
CodeProject is changing. Read more.
Home

Creating Custom Class in JavaScript and adding methods, properties.

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.17/5 (24 votes)

Aug 29, 2006

viewsIcon

61762

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

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

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

Adding new method and property in "MyClass"

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

//Calling Method 
MyObject.MyMethod(); 

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