Claude Pache (2013-12-13T16:20:14.000Z)
If you are not paranoid, you can just use nonwritable properties. That forces you to use `Object.defineProperty` to change the value, so you are protected against accidental assignments.

    function Obj() {
        Object.defineProperty(this, 'x', { value: 2, writable: false, enumerable: true, configurable: true })
        this.setX = function (val) {
            Object.defineProperty(this, 'x', { value: val })
        }
    }

    o = new Obj
    o.x = 17 // assignment will fail; moreover, in strict mode, an error is thrown
    o.x // 2
    o.setX(18)
    o.x // 18

It doesn't prevent the user from hanging themself with `Object.defineProperty(o, 'x', { value: 17 })`; but at least, it won't be by chance!

—Claude


Le 13 déc. 2013 à 14:34, raul mihaila <raul.mihaila at gmail.com> a écrit :

> Hello, was there any proposal for object properties that can be read from anywhere but are writable only from the execution context where the name associated with the property was defined? Something like:
> 
> function Obj() {
>     ro x; // read only name x
>     this.x = 2;
>     this.setX = function (val) {
>         this.x = val;
>     };    
> }
> 
> var o = new Obj;
> 
> o.x; // 2
> o.x = 43; // throws some error
> o.x; // 2
> o.setX(100);
> o.x; // 100
> 
> The advantages would be that you are sure that there are no side effects when the property is accessed and also I'm guessing you have no function call overhead.
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20131213/736dd1da/attachment.html>
domenic at domenicdenicola.com (2013-12-18T03:43:50.677Z)
If you are not paranoid, you can just use nonwritable properties. That forces you to use `Object.defineProperty` to change the value, so you are protected against accidental assignments.

    function Obj() {
        Object.defineProperty(this, 'x', { value: 2, writable: false, enumerable: true, configurable: true })
        this.setX = function (val) {
            Object.defineProperty(this, 'x', { value: val })
        }
    }

    o = new Obj
    o.x = 17 // assignment will fail; moreover, in strict mode, an error is thrown
    o.x // 2
    o.setX(18)
    o.x // 18

It doesn't prevent the user from hanging themself with `Object.defineProperty(o, 'x', { value: 17 })`; but at least, it won't be by chance!