函数返回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
分配了一个空变量。