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

How to use Javascript as OOPS for beginner

4.82/5 (10 votes)
22 Nov 2010CPOL2 min read 26.4K  
Javascript
Hello,
This is my first tips and trick for codeproject. So I decides start from very basic tips on javascript. As most of the beginner developer use javascript something like
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>


This is very basic style to make fucntion and expose that function in different function like in above example function product(a,b) is directly call in body javascript.

This is very simple approach to use javascript. Let try to learn Javascript in more generic term. I will give demo in steps

Step 1: First i would recommend to make external javascript rather then in same html header although this is not mandatory. But for good coding practices Javascript should be separated in file.
Step 2: Create airthmaticOp.js
function airthmaticOperation()
{
}

Step3: as you can see in step 2, i create airthmaticOpration function which in this step i will treated function like a class.
hmmm.. So as you know in class there are methods, so how i can make methods in javascript for my class airthmaticOpration. In javascript special keyword prototype is used in order to make method for class.The prototype object is here to help when you wish to quickly add a custom property to an object that is reflected on all instances of it. To use this object, simply reference the keyword "prototype" on the object before adding the custom property to it, and this property is instantly attached to all instances of the object. A demonstration is worth a thousand words, so I'll show one right now , how to use it in my class airthmaticOperation
airthmaticOperation.prototype.addition = function(a,b)
{
  return a+b;
}

airthmaticOperation.prototype.multiply = function(a,b)
{
  return a*b;
}


Step 4: That looking cool Now how to use it in my function.

first you have to make object as you make in simple class like
var objMyClass = new aithmaticOperation();


Object is created and Now you are ready to access method of my class airthmaticOperation

var resultAdd = objMyClass.addition(a,b);

var resultMul = objMyClass.multiply(a,b);


That's all about it. Its very good approach to make complex javascript and scalable like as OOPS.

License

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