0

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)?

3
  • var in a ctor is allowed. Something else is going funny with your code. Since you've only posted part of it (your example doesn't run), I imagine it's in one of the other parts. Commented Aug 17, 2015 at 16:35
  • Have you looked at returning it from the Engiszi function? Commented Aug 17, 2015 at 16:35
  • may try Math.random(); instead of just random() ? Commented Aug 17, 2015 at 16:38

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I thought it meant the type "Engiszi", but apparently it was this.type. Adding "this." to "type" solved the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.