简体   繁体   中英

function returns function in javascript

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM