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); } } 
1

2 Answers 2

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.

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

2 Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.