Hacker News new | past | comments | ask | show | jobs | submit login
Creating Read-Only References to Objects in JavaScript (bolshchikov.net)
46 points by bolshchikov on Dec 21, 2013 | hide | past | favorite | 11 comments



ES6 will add proxies, another approach.


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


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


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?


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

http://jsbin.com/IvIXUZO/1/edit


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


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.


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


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.


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


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"}




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: