tc39 / proposal-grouped-and-auto-accessors

Grouped Accessors and Auto-Accessors for ECMAScript
https://tc39.es/proposal-grouped-and-auto-accessors
MIT License
54 stars 5 forks source link

Consider adding the ability to return an accessor in a function #16

Open Ocean-OS opened 2 weeks ago

Ocean-OS commented 2 weeks ago

If you want to return a getter and setter in a function, you have to wrap it in an object property. This can limit some abilities to implement more reactivity in ECMAScript. For example:

function logger(value){
    return {
        get value(){
            console.log('Value accessed!');
            return value;
        },
        set value(newVal){
            console.log(`Value changed to ${newVal}!`);
            value = newVal;
            return true;
        }
    }
}
let count = logger(0);
count.value++; //logs Value changed to 1!

is much less convenient and ergonomic than:

function logger(value){
    return accessor {
        get(){
            console.log('Value accessed!');
            return true;
        }
        set(newVal){
            console.log(`Value changed to ${newVal}!`);
            value = newVal;
            return true;
        }
    }
}
let count = logger(0);
count++; //logs Value changed to 1!

Returning accessors would allow for much simpler state management and reactivity in ECMAScript without any extra libraries or build steps. Some examples of where this could be used include:

ljharb commented 2 weeks ago

By definition, an accessor (or a getter/setter) are for a property on an object. A variable isn't a property on an object, it's a binding, and overloading the way operators work for a binding would be a massive proposal unlikely to gain consensus, and either way would need to be separate from this proposal.