我班上有两种方法.一种方法随机化值,另一种方法在表示CSS颜色的字符串中返回这些值.然而,在随机化之后,它仍然始终返回相同的字符串,即使创建的对象中的值已更改.你能解释一下原因吗?
这是jsfiddle:https://jsfiddle.net/wpem1j9e/
function Color(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
this.randomize = function(){
this.r = Math.floor(Math.random() * 100);
this.g = Math.floor(Math.random() * 100);
this.b = Math.floor(Math.random() * 100);
return this;
}
this.toString = function(){
var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
return cssColor;
}
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";
Run Code Online (Sandbox Code Playgroud) javascript ×1