小编Wal*_*alk的帖子

Javascript方法总是返回相同的值

我班上有两种方法.一种方法随机化值,另一种方法在表示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
推荐指数
1
解决办法
76
查看次数

标签 统计

javascript ×1