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:
- use
[]
create new array, notnew array()
, - use capital letters constructor functions,
function map(...) {...}
, notmap(...)
, - don't reference functions before declaring them, put
function generatecity(citynum)
beforethis.generatecity = generatecity
, - use
console.log
, notalert
, - 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
Post a Comment