1

I want to loop on each object(building) of a class in javascript, like doing my own .each() jQuery function (because sometimes, I just need the first buildings, not the whole class). Is there a way to get the index of an element in a Javascript class ? Are the classes structured like an array so I can access to an element like $('.Building)[i] ?

my Class :

 function Building (name, height, width) {
     this.name = name;
     this.height = height;
     this.width = width;
 }

When I add a building to the class :

var b1 = new Building("Building1", 1, 2);
var b2 = new Building("Building2", 3, 4);

And then I want to display them by using a tool like

for (var i=0; i<$('.Building').length; i++){
displayOnMap($('.Building')[i]);
}

Is it possible ? How should I code that ?

EDIT **

@MESSIAH: Sure you can make javascript classes, check here ;) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

@Ralph: No, I am not confusing, actually it works pretty well in my code. the .each() function is not only for the CSS class, but also working on JavaScript class made as seen above. It works like this :

$('.Building').each(function() { 
   getData(this); 
}); 
LaurianeF
  • 27
  • 1
  • 8
  • 3
    You may be confusing regular Javascript classes with CSS classes. It doesn't make sense to me that you are trying to use a jquery css selector to select a javascript object that you've instantiated. – Ralph Caraveo Aug 01 '13 at 17:36
  • there is no such thing like javascript class...and i am sorry i think this question is poorly framed...i cant reach the core of your problem!!! – HIRA THAKUR Aug 01 '13 at 17:38
  • http://stackoverflow.com/questions/2752868/does-javascript-have-classes There are just constructors and protoypes in javascript – HIRA THAKUR Aug 01 '13 at 18:26
  • 1
    @MESSIAH It's not exactly far fetched to still think of a JavaScript constructor with its associated prototypes in terms of a "class". It's still a blue print of which many objects can be instantiated from. – Ralph Caraveo Aug 01 '13 at 19:40

1 Answers1

3

Maybe what you are looking for is to add your Building objects into an array:

var buildings = [];
buildings.push(b1);
buildings.push(b2);

Then, you can loop as you need to:

for (var i=0, len=buildings.length; i < len; i++){
    displayOnMap(buildings[i]);
}
Ralph Caraveo
  • 10,025
  • 7
  • 40
  • 52