21

How would I create an object in jQuery, and then proceed to make a couple of different instances of this object I.e

Create an object named box which holds a variable called color.

And then make a couple of instances of this object with different stored colours.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Ben_hawk
  • 2,476
  • 7
  • 34
  • 59
  • 1
    What are you trying to achieve, exactly? – Andreas Wong Jul 06 '12 at 02:05
  • I want to explore object-oriented jQuery but do not know how to construct a class and then initialise an object – Ben_hawk Jul 06 '12 at 02:07
  • use jquery's[.map()](http://api.jquery.com/jQuery.map/) function – Ohgodwhy Jul 06 '12 at 02:07
  • 3
    This is a job for javascript alone, jQuery is a framework built on javascript with its focus set on DOM manipulation, javascript is a language. It has become a common misconception that jQuery is a language itself. – Austin Jul 06 '12 at 02:08
  • Maybe this might help? [3 ways to define a JavaScript class](http://www.phpied.com/3-ways-to-define-a-javascript-class/) – sachleen Jul 06 '12 at 02:09

4 Answers4

46

Another way to make objects in Javascript using JQuery, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:

var box = {}; // my object
var boxes =  []; // my array

$('div.test').each(function (index, value) {
    color = $('p', this).attr('color');
    box = {
        _color: color // being _color a property of `box`
    }
    boxes.push(box);
});

Hope it helps!

Luis
  • 5,786
  • 8
  • 43
  • 62
11

May be you want this (oop in javascript)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

For more information.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
8

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});
Ben_hawk
  • 2,476
  • 7
  • 34
  • 59
1

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue')enter image description here

Alex Gray
  • 16,007
  • 9
  • 96
  • 118
Control Freak
  • 12,965
  • 30
  • 94
  • 145