5 ms·
Creating Read-Only References to Objects in JavaScript
- TazeTSchnitzel 13y agoES6 will add proxies, another approach.
- bolshchikov 13y agoYes, that would be great. However, the approximate arrival time of ES6 will be exactly the year from now.
- GeneralMayhem 13y agoYou can use them now on Node with the experimental --harmony-proxies flag.
- yeaah 13y agolearn to grammar
- CountHackulus 13y agoWhat if you just did var x = { ...}; var y = Object.create(x); Object.freeze(y); Object.preventExtension(y); Wouldn't that achieve the same effect?
- deleted 13y ago[deleted]
- bolshchikov 13y agoNo, 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 13y agoso just deep-clone your object before freezing / sealing, right?
- Sharlin 13y agoNo 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.
- krebby 13y agoso just deep-clone your object before freezing / sealing, right?
- GowGuy47 13y agoThis seems like a cool idea. What was your need for this solution if you don't mind me asking? Developing a library?
- teleclimber 13y agoI 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 13y agofunction makeRef(x) { return function() { return x; }; }
- deleted 13y ago[deleted]
- effbott 13y agoThis 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"}