Syntax Proposal: Add getter/setter directly on current scope ??
Li Xiaolong schrieb:
Sometimes, we want to get a representation of another variable, or get an abstract representation of some other variables. In this case, we often use getter/setter. But defining a getter/setter in current scope is complex.
Can we make adding a getter or setter to current scope easier like the following example?
var a = 2; get b() {return a+1;} b; //returns 3
You already can do that:
var a = 2;
with({get b() { return a+1; }) {
b // 3
}
However, magic bindings (that do something else than variable assignment
and access) are a source of confusion and usually a bad idea.
Why not simply use a function b()
that you can call? It's clear what
happens with that.
We hardly need a special syntax for getter/setter variables in lexical
scopes.
It does not make sense for me because you already have access to all the values available in the current context, there is no need to make things more complex and to add a getter.
Sometimes, we want to get a representation of another variable, or get an abstract representation of some other variables. In this case, we often use getter/setter. But defining a getter/setter in current scope is complex.
Can we make adding a getter or setter to current scope easier like the following example?
var a = 2; get b() {return a+1;} b; //returns 3
If I want to do this using current syntax, I need to write the following:
var a = 2; Object.defineProperty(this, 'b', {get: function(){return a+1}}); b; //returns 3
It is much more complex than the syntax I advised above. My advice also makes defining a getter/setter in current scope look like defining a getter/setter in an object, which makes it easy to remember.