In JavaScript there is no keyword called Class to create a class
Java Script Class define in 3 ways
1) Using a function
2) Using a Object Literal
3) Singleton using a function
1) Using a function
Using Java Script Function we can create a class.To create a method and variable by using this keyword and function().
After creating a class using new can create a object.
For example : (For Creating a class)
function Animal (breed) {
this.breed = breed;
this.color = "red";
this.getInfo = getAnimalInfo;
}
function getAnimalInfo() {
return this.color + ' ' + this.breed;
}
Then Create a Object using new keyword.
Example:
var Animal = new Animal('dog');
dog.color = "brown";
dog.breed = "combai";
alert(Animal.getInfo());
2) Using String Literal
In Java Script Literals are used to create an objects and arrays.
For Creating Object :
var obj = { }
var obj = new Object();
For Array Creating :
var arr = [];
var arr = new Array();
Example for Creating Class using Literals
// Here no Class Like Concept we can directly write a instance(Object) immediately.
var Animal = {
breed: "combai",
color: "brown",
getInfo: function () {
return this.color + ' ' + this.breed;
}
}
Also, For Calling a class you don't need to create an object.Because object already exists.So you simply start using this instance
For Example :
Animal.bread = "combai";
alert(Animal.getInfo);
3) Singleten Using a function
This way is a combination of above two ways.
You can use a function to define a singleton object.
For Example :
var Animal = new function() {
this.breed = "combai";
this.color = "brown";
this.getInfo = function () {
return this.color + ' ' + this.breed;
};
}
Also,the way to use the object is exactly like String Literal
For Example :
Animal.bread = "combai";
alert(Animal.getInfo);