Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
    }
  }
});
share|improve this question
    
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. – Benjamin Gruenbaum Dec 6 '13 at 16:34
    
@BenjaminGruenbaum simple enough answer, I like it. – wootscootinboogie Dec 6 '13 at 16:36
    
@BenjaminGruenbaum offhand can you think of anything outside of validation were it might be useful to use defineProperty? – wootscootinboogie Dec 6 '13 at 16:37
1  
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. – Benjamin Gruenbaum Dec 6 '13 at 16:41
1  
@tomdemuyt sure, done. – Benjamin Gruenbaum Dec 6 '13 at 18:04
up vote 4 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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