0
\$\begingroup\$

I'm curious about Object.defineProperty. It seems awfully verbose for not doing much more than what you can already do in the constructor. What's the point of it? Would it be 'bad code' to not use it? I know you have more control over read/write and enumerability with defineProperty, is that enough to use this verbose syntax?

function Person(age, name) {
  this.name = name;
  this.age  = age;
};

Object.defineProperty(Person.prototype, "age", {
  get: function() {
    return this._age;
  },

  // Added a few things to demonstrate additional logic on the setter
  set: function(num) {
    num = parseInt(num, 10);
    if(num > 0) {
      this._age = num;
    }
  }
});
\$\endgroup\$
  • \$\begingroup\$ You usually only use defineProperty in very specific cases. (let's say you wanted validation on age?) - in your case - I would not use it. \$\endgroup\$ – Benjamin Gruenbaum Dec 6 '13 at 16:34
  • \$\begingroup\$ @BenjaminGruenbaum simple enough answer, I like it. \$\endgroup\$ – wootscootinboogie Dec 6 '13 at 16:36
  • \$\begingroup\$ @BenjaminGruenbaum offhand can you think of anything outside of validation were it might be useful to use defineProperty? \$\endgroup\$ – wootscootinboogie Dec 6 '13 at 16:37
  • 1
    \$\begingroup\$ Plenty of reasons - non-enumerable properties, frozen properties, computed properties, proxies (Create an object based on another object and mirror calls + observe). There are a lot of good use cases - they're just not very common in the web because of IE8 yet. In your case (age) I would not use Object.defineProperty. \$\endgroup\$ – Benjamin Gruenbaum Dec 6 '13 at 16:41
  • 1
    \$\begingroup\$ @tomdemuyt sure, done. \$\endgroup\$ – Benjamin Gruenbaum Dec 6 '13 at 18:04
4
\$\begingroup\$

As requested by tomdemuyt. I'm posting my comments as an answeR:

You usually only use defineProperty in very specific cases. (let's say you wanted validation on age?) - in your case - I would not use it.

Op then asked:

offhand can you think of anything outside of validation were it might be useful to use defineProperty?

Plenty of reasons:

  • non-enumerable properties,
  • frozen properties,
  • computed properties,
  • proxies (Create an object based on another object and mirror calls + observe).

There are a lot of good use cases - they're just not very common in the web because of IE8 yet. In your case (age) I would not use Object.defineProperty.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.