Javascript – implement class using function

Javascript classes can be created using function. Here a function can be instantiated using new keyword. The member variables and methods in function can be assigned using keyword this.

Here is a basic example code

<script tyle="text/javascript">
function testclass() {
  this.var1 = "value1";
  this.method1 = function () {
    document.write("In method1 var1=" + this.var1 +  "<br/>");
var obj= new testclass();

Additional notes on prototype

Here we defined member function in constructor. In general it is better to define member function in prototype as it will create only one instance of the function even when multiple instances are created.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments