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); } workOut(100);
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){ this.name = theName; //public variable this.age = theAge; this.eat = function(){ document.write(this.name + " 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); p1.eat();
So what’s going on behind the screens?. We will discuss more about them later.