0

I have this piece of code in a constructor function:

    Object.defineProperty(this, "color", {
        get : function() {
            return color;
        },
        set : function(newVal) {
            color = newVal;
            this.path.attr("stroke", color);
        } 
    });

JSHint is warning that 'color' is not defined. Am I supposed to define 'color' somehow before configuring it with defineProperty?

(I have tried using 'this.color' inside defineProperty, but that causes infinite loops)

thanks

devboell
  • 1,180
  • 2
  • 16
  • 34

1 Answers1

1

color is indeed undefined. You need to store the information elsewhere.

You could do it via closure:

var color;
Object.defineProperty(this, "color", {
    get : function() {
        return color;
    },
    set : function(newVal) {
        color = newVal;
        this.path.attr("stroke", color);
    } 
});

Or with another, non-enumerable (so that it doesn't show up on for in) and non-configurable (to avoid overrides) property:

Object.defineProperty(this, "_color", {
  configurable: false,
  writable: true,
  enumerable: false
});

Object.defineProperty(this, "color", {
    get : function() {
        return this._color;
    },
    set : function(newVal) {
        this._color = newVal;
        this.path.attr("stroke", color);
    } 
});
Renato Zannon
  • 28,805
  • 6
  • 38
  • 42