Reputation: 675
I am building a little library for fun and am wondering whether I have hit a design flaw or whether there is a common approach to my problem.
Lets say I have three objects
obj1 = function() {
this.create2 = function() {
return new obj2();
}
}
obj2 = function() {
this.create3 = function() {
return new obj3();
}
}
obj3 = function() {
this.create4 = ......
}
I would like to stop people being able to instantiate obj2
independently (var obj2 = new obj2()
) and force them to use obj1.create2
same for obj2.create3
and so on?
Is there a proper solution to this problem?
Upvotes: 1
Views: 76
Reputation: 21542
There is one thing about your implementation that might be contradictory: the scope of your classes (that by the way you in my honest opinion called wrongly obj
).
Given this snippet:
obj1 = function() {
this.create2 = function() {
return new obj2();
}
}
There are 2 possibilities:
new obj2()
resulting from this.create2()
within obj1 (private)Corresponding solutions:
For case 1: the scope of your class obj2
is then wrong, and you should put the whole definition within obj1
:
obj1 = function() {
obj2 = function() {
this.create3 = function() {
return new obj3();
}
}
this.create2 = function() {
return new obj2();
}
}
For case 2: then the class obj2
is indeed public and you have to leave it that way.
What you may do is leave the objects their public status (public to their immediate outside scope, that is) but nonetheless encapsulate everything within a global object (the api mapper) which, itself, will expose only certain of its methods.
For example:
function api() {
obj1 = function() {
this.create2 = function() {
return new obj2();
}
}
obj2 = function() {
this.create3 = function() {
return new obj3();
}
}
obj3 = function() {
this.create4 = ......
}
this.object1 = new obj1;
this.object2 = new obj2;
this.object3 = new obj3;
}
and now, from anywhere else:
var o1 = api.object1.create2(); //OK: will instanciate a new obj2
var o2 = new obj2; //NOT OK: there's no access to obj2 from here
This is not OOP at all (accessing objects from a class you don't have access to is rather unseen), but as I said it's just a workaround.
I've seen in some frameworks the creator just making everything public, and prefixing "private" methods with "_", adding a comment like "This method/object is meant to be private please don't use outside". I think it's actually fair, thinking of how javascript is designed. Up to you to pick your way.
Upvotes: 4