-1

How can I access the color property of the constructor, from the setColor function?

function Obj() {
  this.color = undefined;
}

Obj.prototype.setColor = () => {
  for (var k = 0, hex = "0123456789ABCDEF", max = hex.length, random, color = ""; k < 6;
    ++k, random = Math.floor(Math.random() * max), color += hex[random]);
  this.color = "#" + color; // Here i need to change
};

var ball = new Obj();
ball.setColor();
console.log(ball.color);

So, I want to run the setColor function and change the color property of Obj the constructor.

What is the most elegant and simple method, without declare a var to the context and use that?

alessandrio
  • 4,282
  • 2
  • 29
  • 40

1 Answers1

1

The constructor doesn't have a color property.

The constructor function adds a color property to the instance as it is constructing it.

You can access the property on the instance with this.color (inside the function on the prototype).

function Obj() {
  this.color = "";
}

Obj.prototype.setColor = function() {
  for (var k = 0, hex = "0123456789ABCDEF", max = hex.length, random, color = ""; k < 6;
    ++k, random = Math.floor(Math.random() * max), color += hex[random]);
  this.color = "#" + color;
};

var instance = new Obj();
instance.setColor();
console.log(instance.color);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335