Reputation: 16335
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?
Upvotes: 0
Views: 134
Reputation: 22438
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
Upvotes: 2
Reputation: 5848
You forgot parens. You have to add () to this.pick_random_colors
Upvotes: 2
Reputation: 52788
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.
Upvotes: 7