

Creating Read-Only References to Objects in JavaScript - bolshchikov
http://blog.bolshchikov.net/post/70680524646/creating-read-only-reference-to-object-in-javascript

======
TazeTSchnitzel
ES6 will add proxies, another approach.

~~~
bolshchikov
Yes, that would be great. However, the approximate arrival time of ES6 will be
exactly the year from now.

~~~
GeneralMayhem
You can use them now on Node with the experimental --harmony-proxies flag.

------
CountHackulus
What if you just did

    
    
      var x = { ...};
      var y = Object.create(x);
      Object.freeze(y);
      Object.preventExtension(y);
    

Wouldn't that achieve the same effect?

~~~
bolshchikov
No, you can still mutate the array and it will influence the original model.

[http://jsbin.com/IvIXUZO/1/edit](http://jsbin.com/IvIXUZO/1/edit)

~~~
krebby
so just deep-clone your object before freezing / sealing, right?

~~~
Sharlin
No need to freeze/seal if you deep-clone; it's not your business what the
recipient does with its own copy. The point is, copying can be expensive. In
C++, you can pass by copy, by reference, or by const reference. The idea is
that a const reference means that the object is not modifiable _through that
reference_ , no matter whether it's itself const or not.

------
GowGuy47
This seems like a cool idea. What was your need for this solution if you don't
mind me asking? Developing a library?

~~~
teleclimber
I am not the developer but it is quite useful if you have Javascript objects
that handle your app's data (the "M" in MVC), and the Views request data
objects from these models.

If you just pass a reference then the View could accidentally alter the data
object which would corrupt all other view's data objects and the Model's copy
as well. Yikes.

My current solution is to create a deep-clone of the data object and pass that
back to each view that asks for it. That way if a View changes the data
object, it doesn't affect the other copies of the data.

The solution presented here also prevents the View from modifying its own copy
(which should help reduce bugs within the View), and it keeps copies of the
object up to date, which is a neat trick.

------
jayferd

        function makeRef(x) { return function() { return x; }; }

~~~
effbott
This doesn't make the target object read-only - it just returns a reference to
it.

    
    
      data = {one: "one"}
      ref = makeRef(data)
      ref().two = "two"
      
      data
      => Object {one: "one", two: "two"}

