Javascript function can be used to define classes. Inside classes, member properties (containing functions, objects, etc.) can be defined either as member variables in constructor or using function prototype members. Some comments on using Javascript prototype
- Prototype member property is shared by all instance of the class. Hence new instance does not recreate the method.
- Changing the prototype method, changes it for all instances.
- When a property is not found in instance of class, it is looked up in prototype. If same property is defined in instance and prototype, one in instance is used.
Defining function in constructor example
Here we are defining member function in constructor which will create separate instance of function with each class instance. The counter count
set in function will not be shared among instances.
<script type="text/javascript"> function testclass() { this.v1 = "value1" this.f1 = function () { arguments.callee.count = arguments.callee.count || 0; arguments.callee.count++; document.write("function counter: " + arguments.callee.count + "<br/>") } } var o1 = new testclass(); var o2 = new testclass(); if (o1.f1 === o2.f1) { document.write("o1.f1 and o2.f1 are same <br/>"); } else { document.write("o1.f1 and o2.f1 are not same <br/>"); } o1.f1() o2.f1() </script>
Defining function in prototype example
Here we are defining member function in prototype which will use same instance of function with each class instance. The counter count
set in function will be shared among all instances. Unless there is a specific reason, it is better to set functions in prototype.
<script type="text/javascript"> function testclass() { this.v1 = "value1" } testclass.prototype.f1 = function () { arguments.callee.count = arguments.callee.count || 0; arguments.callee.count++; document.write("function counter: " + arguments.callee.count + "<br/>") } var o1 = new testclass(); var o2 = new testclass(); if (o1.f1 === o2.f1) { document.write("o1.f1 and o2.f1 are same <br/>"); } else { document.write("o1.f1 and o2.f1 are not same <br/>"); } o1.f1() o2.f1() </script>