Custom Objects in JavaScript

Custom objects are user-defined object where user can create its own object and it behaves exactly how the user wants it. We can create object by using the following steps:

  • We can define an object by using an object function.
  • Later on, instantiate new object by using “new” keyword.

JavaScript Custom Object Syntax

function userobject(parameter)
{
}

Where,

  • userobject: It is the unique name of the function.
  • parameter: It is used to pass parameter in the function.

JavaScript Custom Object Example

<!DOCTYPE html>
<head>
<script type="text/javascript">
	function bike(company, name)
	{

		bike.company = company;
		bike.name = name;
	}

	var mybike = new bike("Bajaj", "Pulsar");

	document.write("Name of the company: " + bike.company + "<br>");
	document.write("Name of the bike: " + bike.name);
</script>
</head>
<body>

</body>
</html>
  • In the above program we have created custom objects that is user-defined object.
  • We have created our own object called bike which is unique name of the function and we have passed the parameters company and name.
  • var mybike = new bike(“Bajaj”, “Pulsar”); line contains variable name called “mybike” and created object called “bike” by using “new” keyword and we are passing the parameter values to that object.
  • document.write(“Name of the company: ” + bike.company + “<br>”); is used to display the company name and bike name in the output.

JavaScript Custom Object Demo

  • Save the file as customObject_example.html in eclipse IDE.
  • Select the file and right click on the file.

When the execution process is completed successfully we will get the following output:

JavaScript Custom Objects Demo

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*