top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create a class in Java Script?

0 votes
402 views
How to create a class in Java Script?
posted Jun 26, 2014 by Ujjwal Mehra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

// Define a class like this
function Person(name, gender){

// Add object properties like this
this.name = name;
this.gender = gender;
}

// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
}

// Instantiate new objects with 'new'
var person = new Person("Bob", "M");

// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"

answer Jun 27, 2014 by Shiva Chawala
0 votes

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);
answer Jun 27, 2014 by Pardeep Kohli
Similar Questions
0 votes

I need to execute some function while pasting in web page. Can any tell me to solve this issue?This can be possible in Java Script or Jquery?

0 votes

Please give the example for both.

...