This can more or less achieved with getters/setters:

```js
function Obj() {
    var x = 'foo';
    Object.defineProperty(this, 'x', {
        get: function() {
            return x;
        },
        set: function() {
            throw new Error('Cannot set property "x"!');
        }
    });
}

var obj = new Obj();
console.log(obj.x); // 'foo'
obj.x = 'bar'; // Error!
```

I think ES6 classes will provide some nicer facilities, but I'm not current
on how a public getter / private setter pattern would be achieved outside
of `Object.defineProperty()` at this point.


On Fri, Dec 13, 2013 at 8:34 AM, raul mihaila <[email protected]>wrote:

> 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
> [email protected]
> https://mail.mozilla.org/listinfo/es-discuss
>
>


-- 
Jeremy Martin
661.312.3853
http://devsmash.com
@jmar777
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to