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;
}
}
});
-
\$\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– Benjamin Gruenbaum2013年12月06日 16:34:41 +00:00Commented Dec 6, 2013 at 16:34
-
\$\begingroup\$ @BenjaminGruenbaum simple enough answer, I like it. \$\endgroup\$wootscootinboogie– wootscootinboogie2013年12月06日 16:36:16 +00:00Commented Dec 6, 2013 at 16:36
-
\$\begingroup\$ @BenjaminGruenbaum offhand can you think of anything outside of validation were it might be useful to use defineProperty? \$\endgroup\$wootscootinboogie– wootscootinboogie2013年12月06日 16:37:57 +00:00Commented Dec 6, 2013 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– Benjamin Gruenbaum2013年12月06日 16:41:16 +00:00Commented Dec 6, 2013 at 16:41
-
1\$\begingroup\$ @tomdemuyt sure, done. \$\endgroup\$Benjamin Gruenbaum– Benjamin Gruenbaum2013年12月06日 18:04:26 +00:00Commented Dec 6, 2013 at 18:04
1 Answer 1
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
.