Note that there are some explanatory texts on larger screens.

plurals
  1. POremoving public access to methods on an object
    primarykey
    data
    text
    <p>I would like to take an object and remove some methods from it. </p> <p>i.e. I have internally have an object with getter/setters on it and I want to give external users access to it. I don't want them to have access to the setter functions.</p> <p>I don't want to change original object reference by removing methods from it but create a new object reference that points to the same object but has less methods on it.</p> <ul> <li>How would I go about doing this?</li> <li>Is this a design-pattern?</li> <li>Are there well known solutions for these kinds of problems?</li> </ul> <p>I have an implementation of this function </p> <pre><code>var readOnly = function(obj, publicData) { // create a new object so that obj isn't effected var object = new obj.constructor; // remove all its public keys _.each(object, function(val, key) { delete object[key]; }); // bind all references to obj _.bindAll(obj); // for each public method give access to it _.each(publicData, function(val) { object[val] = obj[val]; }); return object; }; </code></pre> <p>See <a href="http://jsfiddle.net/Raynos/tykBJ/15/" rel="nofollow">live example</a>, <a href="http://documentcloud.github.com/underscore/#each" rel="nofollow"><code>_.each</code></a> <a href="http://documentcloud.github.com/underscore/#bindAll" rel="nofollow"><code>_.bindAll</code></a></p> <p>For all intended purposes the object returned should be the same as the original object except some of the methods aren't there anymore. The internal <code>this</code> reference should not break in any of the functions. The prototype chains should not break.</p> <ul> <li>What would be an intuitive name for such a function?</li> <li>Are there any pitfalls with my current implementation that I should be aware of?</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload