0

I have an array this.colors = [RED, BLUE, GREEN], and sometimes I would like to pick one random color from this array. When I doing it by this way, the result is normal:

rand_color = this.colors[Math.floor(Math.random() * this.colors.length)]
javascript: console.log(rand_color)
// => rgb(211, 65,  65)

But when I've wrapped it in the function:

this.pick_random_color = function() {
    return this.colors[Math.floor(Math.random() * this.colors.length)];
}

that function doesn't return random value. Instead, I get this message in the log:

color = this.pick_random_color;
javascript: console.log(color); 
// => this.pick_random_color = function() {
// =>   return this.colors[Math.floor(Math.random() * this.colors.length)];
// => }

What's wrong with the function?

1
  • 2
    I'm pretty sure your use of this is obfuscating your code, it is totally unnecessary. DaveShaw is 100% right, you are assigning a null variable to color in this case. Commented Nov 27, 2011 at 20:55

3 Answers 3

7

Don't you need parentheses after the call to pick_random_color?

color = this.pick_random_color();

What you appear to be doing is assigning color to the pick_random_color function, not executing it.

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

Comments

2

You forgot parens. You have to add () to this.pick_random_colors

Comments

2

That is because this.pick_random_color is a reference to a function. You should execute this function by writing this.pick_random_color().

But make sure the this keywords refers to the original object

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.