I am thinking about passing a private variable of one class into another class, for some belonging case like 'company --> department --> employee'. As an employee can tell some information of his company, there's some private variables I'd like to pass.
I think this relationship is not as same as common class and supClass. As an employee is not a type of department and a department is not a type of company (if I am wrong, please tell me more).
So in a case like this, is it a good idea to use nested constructor functions?
For example: http://jsfiddle.net/JsJJ9/
function TeamClass(name){
var pass = "privateVariable"
var slot = 1;
this.members = []; // I have a list of members
this.name = name;
this.add = function(){ //add member into this team
var m = new MemberClass(slot++);
this.members.push(m)
}
function MemberClass(id){ //here comes the Nested class
var id = id;
this.report = function(){
alert('#'+id+' : Hello, i got some '+pass+'! ')
//So, this member can tell some private data of his team.
}
}
}
class01 = new TeamClass('Team A');
class01.add();
class01.add();
class01.members[0].report();
class01.members[1].report();
Also, I have tried to let the nested class can call the upper level's public variable. I have a function like this:
//at upper level class
m.setBelonging(this)
and
//at belonging class
var team = ''
this.setBelonging = function(theOdj){
team = theOdj;
}
(or see it at http://jsfiddle.net/JsJJ9/1/)
Any comment about this approach?
Added at 2014-01-11 :
Actually, I am trying to ask how can I pass some variable that can't change outside the class (which in my understand, a private variable) to another class. And i found out may be i can do this by nested class. But I don't know is there any defects or there's some better approach.
this.
after a while, at that point you can look into IIFEs. \$\endgroup\$var pass = "privateVariable"
appears to be a placeholder. Could you put the real code in the question so that we can better understand your intention? It's hard to give advice for hypothetical situations. \$\endgroup\$