Hi, > function Contained () > { > var self=this; > self.var1=1; > self.var2=2; > self.method1=function () > { > }; > } > > function Container () > { > var self=this; > self.varA = 'a'; > self.varB = 'b'; > self.containedObj = new Contained; > } > > var foo = new Container; > > Now suppose I want to access variables of Container from within > Contained, for example I might want method1 to return the value of > varA in Container. How would I go about doing this?
As in all OO-Languages you don't. Examples in other languages: Java ---- class Conainted { public int var1; public int var2; public Contained() { var1 = 1; var2 = 2; } public void method1() {...} } class Container { public String varA; public String varB; public Container() { varA = 'a'; varB = 'b'; } public Contained containedObj; } (new Container()).containedObj.method1(); //How could method1 ever access varA? ---- C++ ---- class Contained { public: int var1, var2 Contained(); void method1(); }; class Container { public: std::string varA; std::string varB; Container(); Contained containedObj; }; Contained::Contained(): var1(1), var2(2) {}; void Contained::method1() {...} Container::Container(): varA("a"), varB("B") {}; (new Container()).containedObj.method1(); //How could method1 ever access varA? ---- You may give the container as a parameter to method1: Java: ---- class Conainted { ... public void method1(Container c) { System.out.println(c.varA); ... } } ---- C++: ---- class Contained { public: ... void method1(Container* c); }; void Contained::method1(Container* c) { cout << c->varA << endl; ... } ---- JavaScript: ---- function Contained () { this.var1=1; this.var2=2; this.method1=function (c) { alert(c.varA); }; } ---- Christof