jeudi 14 avril 2016

JavaScript accessor properties in constructors

I've seen accessor properties defined via the get and set keywords in object literals and property descriptors.

(From Speaking JavaScript):

// Object literal
var obj = {
    get foo() {
        return 'getter';
    },
    set foo(value) {
        console.log('setter: '+value);
    }
};

// Property descriptor
var obj = Object.create(
    Object.prototype, {  // object with property descriptors
        foo: {  // property descriptor
            get: function () {
                return 'getter';
            },
            set: function (value) {
                console.log('setter: '+value);
            }
        }
    }
);

(From Eloquent JavaScript):

// Adding to an object's prototype
Object.defineProperty(TextCell.prototype, "heightProp", {
  get: function() { return this.text.length; }
});

But say you're using a constructor to create objects. I haven't seen examples of an accessor being defined within a constructor itself (i.e. so that the accessor is an own property of an object.)

Using Object.defineProperty in the constuctor seems to work:

function V(x, y) {
    this.x = x;
    this.y = y;
    // accessor (getter) `length`
    Object.defineProperty(this, 'length', {
      get: function () { return Math.sqrt(this.x*this.x + this.y*this.y); } // (1)
    });
}

Is there any difference in the accessor property defined as in (1) in the constructor above, and accessor properties defined as in the earlier patterns (object literals, property descriptors directly on the object)?

(And are there objective reasons not to define getters and setters in constructors outside of coding style preference?)

Aucun commentaire:

Enregistrer un commentaire