0

I'm trying to write some objects using JavaScript. I have 1 small object that appears to be working but this object needs a multi-dimensional array.

When I try to use this snippet of this object my browser crashes...

Are there any good tutorials on how to write objects in javascript?

function map(sizeX, sizeY)
{
    var cityArr = new Array();
    this.sizeX = sizeX;
    this.sizeY = sizeY;
    this.generateCity = generateCity;
    var cityXY = new Array();

    function generateCity(cityNum)
    {
        alert(cityNum);
    }
}

When I call this, it fails when I add the call to generateCity method my browser cashes.

var objMap = new map();
//objMap.generateCity(2);

What am I doing wrong?

webdad3
  • 8,893
  • 30
  • 121
  • 223

1 Answers1

3

First off, some JavaScript best practices:

  1. use [] to create a new array, not new Array(),
  2. use capital letters for constructor functions, so function Map(...) {...}, not map(...),
  3. don't reference functions before declaring them, so put your function generateCity(cityNum) before your this.generateCity = generateCity,
  4. use console.log, not alert,
  5. if you're building an object, define your object as one by putting its function on its prototype.

That means doing this:

function Map(sizeX, sizeY)
{
   this.sizeX = sizeX;
   this.sizeY = sizeY;
   // you're not using these arrays. Why are they in your example code?
   var cityArr = [],
       cityXY = [];  
}

Map.prototype = {
  sizeX: 0, // Some default values, shared by all instances
  sizeY: 0, // unless overriden in the constructor function.
  generateCity: function(cityNum) { 
    // let's not block the entire page by using alert.
    console.log("cityNum: " + cityNum);
  }
}

So, with that said, this code works just fine, as can be seen on http://jsfiddle.net/mtr24 (run with your console open, and you'll see "cityNum: 2" being printed.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • Ok I think I need to step back and understand how to create Javascript objects before I go any further. Do you have any tutorial URLs that would benefit me? I want to make sure I'm doing it correctly more than just having it work. – webdad3 Jul 22 '13 at 12:49
  • @webdad3 To continue shamelessly plugging my answer on prototype and constructor functions, inheritance and overriding functions you can check out this answer: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 If you have any question I'll be happy to answer them. – HMR Jul 22 '13 at 13:39
  • +1 for mentioning the prototype but setting the prototype like you do will direct the Map.prototype.constructor to Object instead of Map – HMR Jul 22 '13 at 13:42
  • relevant for inheritance, not necessarily relevant in this case. That said, worth mentioning. – Mike 'Pomax' Kamermans Jul 22 '13 at 19:37