Javascript方法总是返回相同的值

时间:2017-03-30 18:07:34

标签: 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%)";

3 个答案:

答案 0 :(得分:6)

因为在你的toString函数中,你使用rgb而不是this.rthis.gthis.b。前者是构造函数参数。

答案 1 :(得分:1)

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(" + this.r + "%," + this.g + "%," + this.b + "%)"; //new
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
output = function () {
    var outputDiv = document.getElementById("output");
    outputDiv.innerHTML = outputDiv.innerHTML + "<br>" + color1.r + "   " + color1.g + "   " + "   " + color1.b + "<br>" + color1.toString() + "<br>";
}
output();
document.getElementById("input").onclick = function(){
    color1.randomize();
  output();
};

答案 2 :(得分:1)

你可以放弃使用this来缓解一大堆混乱。它没有任何好处。

function color(r, g, b) {
  var me = {
    randomize: function() {
      r = Math.floor(Math.random() * 100);
      g = Math.floor(Math.random() * 100);
      b = Math.floor(Math.random() * 100);
      return me;
    },
    toString: function() {
      var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
      return cssColor;
    }
  };

  return me;
}
var color1 = color(1, 1, 1);
console.log(color1.randomize().toString());