Standard text for accessor/read only properties #195
Replies: 3 comments 5 replies
-
There are two types of read-only properties: const obj = {};
Object.defineProperty(obj, "readonly1", {
value: 1,
configurable: false,
writable: false,
});
Object.defineProperty(obj, "readonly2", {
get() {
return 2;
},
set: undefined,
configurable: false,
}); Both would silently fail in sloppy mode and throw in strict mode. The first one is an actual "read-only" property since it's a data property. The second one is a "getter-only" property. They are already represented differently in our docs:
|
Beta Was this translation helpful? Give feedback.
-
Speaking of the practical difference between a readonly data property and a getter-only accessor property. It's really minor, but it affects how subclassing works (and is the entire reason why the RegExp flag properties are moved from data to accessor properties). class RegExp {
get flags() {
// Pretend it actually reads the internal data structure
return "dgi";
}
}
class BetterRegExp extends RegExp {
get flags() {
console.log("Getting flags");
return super.flags;
}
}
console.log(new BetterRegExp().flags);
// Getting flags
// dgi On the other hand, because all data properties are defined on RegExp instances instead of on its prototype, you can't make these "enhancement properties" that easily. If the class RegExp {
constructor() {
Object.defineProperty(this, "flags", { value: "dgi" });
}
}
class BetterRegExp extends RegExp {
get flags() {
console.log("Getting flags");
return super.flags;
}
}
console.log(new BetterRegExp().flags);
// dgi |
Beta Was this translation helpful? Give feedback.
-
Regarding,
As WebAssembly is a W3C spec., not ECMA, I would suggest that it wholly take after Web APIs. As examples:
|
Beta Was this translation helpful? Give feedback.
-
Properties can be read-only or may be both read and written. The different areas of the docs seem to have standard ways of identifying them, but they are different.
bar
read-only property of thefoo
interface. Read/write properties are assumed (so they just omit "read-only").Web APIs also use the
{{readonly_inline}}
macro in the parent interface to show that the item is read-only. I'm not sure whether javascript does the same thing or not, but it certainly omits it for this case: TypedArray.length.What pattern should we use for Web Assembly.
I think we should adopt the same pattern everywhere - silly to have different words for exactly the same thing. My preference is to use the WebAPI approach - I think "read-only" is more accessible to more people than
accessor
, and also matches up with the macro.I'd probably be even happier with a metadata bases approach for indicating this, in the same way as we are heading towards for static methods, properties etc. Why? Because then we can in theory match up to the IDL to automate we are getting things right and check changes.
Beta Was this translation helpful? Give feedback.
All reactions