Print Shortlink

Classes in JavaScript

JavaScript is a functional Object-Oriented language. The language’s first class citizens are functions. Functions can be assigned as literals to variables as shown below.

var workOut = function(calories){
    document.write("Burning " + calories + " calories);

Functions can also be invoked with a new keyword. This feature in JavaScript paves way for writing some traditional Object-Oriented code.
Say you want to create a class with variables and methods in JavaScript, instantiate it just like you do in C#/Java. Let’s create a class Person with name and age attributes and eat method.

  function Person(theName,theAge){ = theName; //public variable
     this.age = theAge; = function(){
        document.write( + " is eating");

If you want to now create an object of Person and invoke it’s eat method you can use the new keyword similar to other OO languages.

   var p1 = new Person("Sam",23);;

So what’s going on behind the screens?. We will discuss more about them later.

Leave a Reply