Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数返回javascript中的函数_Javascript - Fatal编程技术网

函数返回javascript中的函数

函数返回javascript中的函数,javascript,Javascript,我有一个数组this.colors=[红、蓝、绿],有时我想从这个数组中随机选择一种颜色。 当我这样做时,结果是正常的: rand_color = this.colors[Math.floor(Math.random() * this.colors.length)] javascript: console.log(rand_color) // => rgb(211, 65, 65) 但当我将其包装到函数中时: this.pick_random_color = function() {

我有一个数组
this.colors=[红、蓝、绿]
,有时我想从这个数组中随机选择一种颜色。 当我这样做时,结果是正常的:

rand_color = this.colors[Math.floor(Math.random() * this.colors.length)]
javascript: console.log(rand_color)
// => rgb(211, 65,  65)
但当我将其包装到函数中时:

this.pick_random_color = function() {
    return this.colors[Math.floor(Math.random() * this.colors.length)];
}
该函数不返回随机值。相反,我在日志中得到以下消息:

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

这个函数有什么问题

调用
pick\u random\u color
后不需要括号吗

color = this.pick_random_color();

您所做的似乎是将
color
分配给
pick\u random\u color
函数,而不是执行它。

您忘记了parens。您必须将()添加到此.pick_random_colors

这是因为
此.pick_random_color
是对函数的引用。您应该通过编写
this.pick\u random\u color()
来执行此函数


但是要确保
这个
关键字是指原始对象

我很确定你使用
这个
会混淆你的代码,这是完全没有必要的。DaveShaw是100%正确的,在本例中,您为
color
分配了一个空变量。