Javascript, inner classes, and how to access parent scope efficiently

It would probably help you out if you do away with notions like "type", "class", etc. when dealing with javascript. In javascript, there is no differentiation from "type", "class", "function", "instance", or "object" -- it's "object" all the way down.

Since every "type" is an "object" and is mutable, you get nothing of the sort of strong-typed efficiency gains you might get from Java or C++ by reusing a single type definition. Think of the "new" operator in javascript as something like "clone the definition and call the constructor", after which the definition of the instance could still be changed.

So go with your first, working example: you won't get any gains by doing something different.


This is what I came up after many hours:

var Parent = function() {
  this.name = "Parent";

  this.Child = Child;
  this.Child.prototype.parent = this;
}

var Child = function() {

}

var parent = new Parent();
var child = new parent.Child();

console.log(child.parent.name);

This way you can instantiate as many Parents as you want, with their Childs underneath, and every Child instance will have access to it's parent instance through the variable parent.