declaring array in javascript object crashes browser -


i'm trying write objects using javascript. have 1 small object appears working object needs multi-dimensional array.

when try use snippet of object browser crashes...

are there tutorials on how 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 call this, fails when add call generatecity method browser cashes.

var objmap = new map(); //objmap.generatecity(2); 

what doing wrong?

first off, javascript best practices:

  1. use [] create new array, not new array(),
  2. use capital letters constructor functions, function map(...) {...}, not map(...),
  3. don't reference functions before declaring them, put function generatecity(citynum) before this.generatecity = generatecity,
  4. use console.log, not alert,
  5. if you're building object, define object 1 putting function on prototype.

that means doing this:

function map(sizex, sizey) {    this.sizex = sizex;    this.sizey = sizey;    // you're not using these arrays. why in example code?    var cityarr = [],        cityxy = [];   }  map.prototype = {   sizex: 0, // default values, shared instances   sizey: 0, // unless overriden in constructor function.   generatecity: function(citynum) {      // let's not block entire page using alert.     console.log("citynum: " + citynum);   } } 

so, said, code works fine, can seen on http://jsfiddle.net/mtr24 (run console open, , you'll see "citynum: 2" being printed.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -