I would like to take an object and remove some methods from it.
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.
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.
- How would I go about doing this?
- Is this a design-pattern?
- Are there well known solutions for these kinds of problems?
I have an implementation of this function
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;
};
See live example, _.each
_.bindAll
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 this
reference should not break in any of the functions. The prototype chains should not break.
- What would be an intuitive name for such a function?
- Are there any pitfalls with my current implementation that I should be aware of?
What you should do is use a Facade Pattern that only has the methods you want to keep and Delegation Pattern to delegate those methods to an instance of the original object. With the rich reflection that is available with Javascript you should be able to generate these Facades programmaticlly fairly easily.