1

I'm new to creating objects in JavaScript. I need to make a random number generator that doesn't repeat itself too often (I have not tried to implement that part in the code snippet below). How can I access n from function RNG(n) in RNG.prototype.rand? It's showing up as unreachable in my editor the way I have it written now. I'm also not sure if I should return from RNG or RNG...rand():

function RNG(n) {
  this.n = n;  
}

RNG.prototype.rand = function() {
  var arr = [];
  var num = Math.floor(Math.rand()*n);

  //keep array of generated numbers
  if(num < arr[0]){
    arr.unshift(num);
  }
  else{
    arr.push(num);
  }
}
honk
  • 9,137
  • 11
  • 75
  • 83
user137717
  • 2,005
  • 4
  • 25
  • 48
  • [`.n` is a property, but you use it like a variable](http://stackoverflow.com/q/13418669/1048572) – Bergi Dec 05 '14 at 05:55

2 Answers2

3

In your code you want this.n rather than n. Unlike some languages, 'this' is not assumed.

To answer your other question, the way you have it set here, you want to return from rand, though to be frank I don't see why you wouldn't just take n as a param to rand() instead of making a stateful object w/ a constructor and whatnot.

Paul
  • 35,689
  • 11
  • 93
  • 122
  • I'm working on an exercise on code wars and this is how it is given. If you can think of any benefits this method might yield, I would be happy to hear them. Does "this" in Jscript work the same as it does in Java? – user137717 Dec 05 '14 at 05:41
  • Generally,if you have more data you want to share across a number of functions, you'd use this pattern. `this` is similar to the Java version, but I would not say it works exactly the same, no. – Paul Dec 05 '14 at 06:06
2

this.n is an instance property which created when you instantiate the instance:

function RNG(n) {
    this.n = n;  
}

var rng = new RNG(5);
console.log(rng.n); // 5

RNG.prototype.rand is an instance method. Within the method, if you want to reference the instance itself, you should use this as well.

function RNG(n) {
    this.n = n;  
}
RNG.prototype.method = function() {
    console.log(this.n);
};

var rng = new RNG(7);
rng.method(); // 7, within this method `this` is `rng`, so `this.n` gives you `rng.n`

If you try this code:

function RNG(n) {
    this.n = n;  
}
RNG.prototype.method = function() {
    var n = 3;
    console.log(n, this.n);
};

var rng = new RNG(7);
rng.method(); // 3, 7

Here without this., n is actually trying to get a variable defined with var n = 3;. It has nothing to do with the instance property rng.n

And finally, if you don't define n:

function RNG(n) {
    this.n = n;  
}
RNG.prototype.method = function() {
    console.log(n);
};

var rng = new RNG(7);
rng.method(); // ReferenceError: n is not defined
Leo
  • 13,428
  • 5
  • 43
  • 61