Walk
Walk

Reputation: 757

Javascript method always returns same value

I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's 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%)";

Upvotes: 1

Views: 566

Answers (3)

JLRishe
JLRishe

Reputation: 101682

You can alleviate a whole lot of confusion by just ditching the use of this. It provides no benefit here.

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());

Upvotes: 1

Christian Carrillo
Christian Carrillo

Reputation: 414

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();
};

Upvotes: 1

Francis
Francis

Reputation: 3383

Because in your toString function you are using r, g and b instead of this.r, this.g and this.b. The former are you constructor parameters.

Upvotes: 6

Related Questions