[英]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. 我有一个数组
this.colors = [RED, BLUE, GREEN]
,有时我想从该数组中选择一种随机颜色。 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
? 调用
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. 您似乎正在做的是将
color
分配给pick_random_color
函数,而不执行它。
You forgot parens. 你忘了原谅。 You have to add () to this.pick_random_colors
您必须将()添加到this.pick_random_colors
That is because this.pick_random_color
is a reference to a function. 那是因为
this.pick_random_color
是对函数的引用。 You should execute this function by writing this.pick_random_color()
. 您应该通过编写
this.pick_random_color()
执行此功能。
But make sure the this
keywords refers to the original object 但请确保
this
关键字引用原始对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.