user2142786
user2142786

Reputation: 1482

how to create a class in jquery?

I'm a newbie in jQuery. I want to create a class in which one variable will be string and another will be an array. for this i am using this code.

var Animal = Class.create({
  init: function(name, sound) {
    this.name = name;
    this.sound = sound;
  }

});
var arr= new Array();
arr.push['kitty'];
arr.push['mitty'];
var cat = new Animal(arr,'meow' );
jsonString = JSON.stringify(cat);
alert(jsonString);

but i'm geeting my array value empty in alert. can anybody please guide me

Upvotes: 0

Views: 273

Answers (1)

Christos
Christos

Reputation: 53958

In JavaScript there are no classes. You could mimic the way we create objects in C# or JAVA for instance like below:

function Animal(name, sound)
{
    this.name = name;
    this.sound = sound;
}

var animal = new Animal("name","sound");

This is called the constructor pattern. Notice that by convention the name of the function that mimics the concept of a class declaration starts with a capital letter.

Update

I am talking about ES5. The next version of JavaScript will contain a concept similar to classes. @silviu-burcea thanks for your comment.

is there any way to create an object whose parameter will an array and a string variable. and pass it through ajax call

Yes it is possible. For instance,

// The constructor for a Zoo.
function Zoo(animals, name)
{
    this.animals = animals;
    this.name = name;
}

// Let's create a Zoo
var zoo = new Zoo(["Dog","Cat","Fish","Bird"], "Welcome to the Jungle");

Then you could pass this object, zoo, the same way you would do with any other object in a ajax call.

$.ajax({
    url: 'your url',
    method: ...,
    cache: ...,
    data: zoo,
    success: function(){
        // the statements that would be executed 
        // if the ajax call be successful.
    }
});

Upvotes: 3

Related Questions