cachaito
2/28/2014 - 11:16 PM

Ciekawe użycie metody toString()

Przykład z: http://designpepper.com/blog/drips/using-javascripts-tostring-method. Przykład 2 wykorzystuje fakt, że każdy obiekt ma metodę toString np. alert({}), console.log(new Date); What do each of these things have in common? They are each providing a string representation of their values, but their internal values are quite different.

//boring
function Color (r, g, b) {
  this.r = r;
  this.g = g;
  this.b = b;
  this.text = "rgb(" + r + ", " + g + ", " + b + ")";
}

var red = new Color(255, 0, 0);

// Outputs: "rgb(255, 0, 0)"
alert(red.text);

/* wady
1. musimy pamiętać o wywołaniu właściwośći .text aby uzyskać kolor
2. gdy w red.r = 100, red.text dalej będzie wskazywał na 255
*/

//nice
function Color (r, g, b) {
  this.r = r;
  this.g = g;
  this.b = b;
}

Color.prototype.toString = function () {
  return "rgb(" + this.r + ", " +
                  this.g + ", " +
                  this.b + ")";
};

var red = new Color(255, 0, 0);

alert(red);// Alerts: "rgb(255, 0, 0)"
var message = 'red is: ' + red; //outputs red is: rgb(255, 0, 0)