sisisisi
sisisisi

Reputation: 621

javascript: defining var in constructor makes it unusable

I have written this code in javascript:

var engiszik;
var numOfCitizens = 10;

function Engiszi()
{
  var chance = random(0, 100);
  this.type = chance < 67 ? "r" : (chance < 87 ? "o" : "p");
  this.mood = ((type === "o") ? random(60, 100, false) : (type === "p" ? random(0, 20) : random(0, 100, false)));
  this.changePlace = random(0, 15, false);
}

initialize();
function initialize()
{
  engiszik = [];
  for(var i = 0; i < numOfCitizens; i ++)
    engiszik.push(new Engiszi());
}

random works correctly and returns a number. The ?: parts also seem to be correct (not entirely sure: can the lack of parentheses cause errors in it?).

When I load the page, I get the error "type not found" at the line engiszik.push(new Engiszi());. If I remove the variable chance from the constructor of Engiszi (and the things that use it), it seems to work.

What causes this? Does the var in the constructor change Engiszi into a normal function instead of a constructor? How can I find a way around this (I really need chance, but I don't want to declare it as a global variable if possible)?

Upvotes: 0

Views: 43

Answers (1)

Paul S.
Paul S.

Reputation: 66304

Lets follow where the error is coming from back beyond the invocation line

"type not found" at the line engiszik.push(new Engiszi());

Step into new Engiszi(), look for type,

this.mood = ((type === "o") ? random(60, 100, false) : (type === "p" ? random(0, 20) : random(0, 100, false)));
//            ^^^^                                      ^^^^

Where is type defined? did you mean this.type?

Upvotes: 3

Related Questions