0

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

3
  • jQuery doesn't have classes, and what is Class supposed to be in that code ? Commented Feb 3, 2015 at 11:43
  • i want to create an object in which one will be array variable and another will be a simple variable. and want to pass it through ajax call Commented Feb 3, 2015 at 11:46
  • Class.create sound like prototype.js-Style: api.prototypejs.org/language/Class/create Commented Feb 3, 2015 at 11:47

1 Answer 1

3

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.
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

is there any way to create an object whose parameter will an array and a string variable. and pass it through ajax call
Javascript has link-object delegation via prototype inheritance, and you can implement you classic class-based inheritance over it. Or use ES6 classes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.