code_junkie

Structs in Javascript

Nov 14th, 2011
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. function Item(id, speaker, country) {
  2. this.id = id;
  3. this.speaker = spkr;
  4. this.country = country;
  5. }
  6. var myItems = [
  7. new Item(1, 'john', 'au'),
  8. new Item(2, 'mary', 'us')
  9. ];
  10.  
  11. var o = {
  12. 'a': 3, 'b': 4,
  13. 'doStuff': function() {
  14. alert(this.a + this.b);
  15. }
  16. };
  17. o.doStuff(); // displays: 7
  18.  
  19. function makeStruct(names) {
  20. var names = names.split(' ');
  21. var count = names.length;
  22. function constructor() {
  23. for (var i = 0; i < count; i++) {
  24. this[names[i]] = arguments[i];
  25. }
  26. }
  27. return constructor;
  28. }
  29.  
  30. var Item = makeStruct("id speaker country");
  31. var row = new Item(1, 'john', 'au');
  32. alert(row.speaker); // displays: john
  33.  
  34. {id: 1, speaker:"john", country: "au"}
Add Comment
Please, Sign In to add comment