Brett's Blog
Edit     New

Friday, February 20, 2009

Subobjects

While I'd guess that the following might be called private classes (though they seem different from those defined at Wikipedia), I don't know what the objects created to function inside of another object would be called. This is not mere namespacing because the subobject (I'm hesitant to call them child/parent objects in order to avoid confusion with subclasses) has access to the superobject as well as to its own methods and properties. If anyone can help with terminology, let me know.

But anyways, I just wanted to point out, if this wasn't already a readily familiar pattern, that there is a way to define private classes which can be instantiated within another class object, while having access to its own methods and properties (including instance ones, and private ones if we wish), as well as those of the object above it.


var Constructor = function () {
var _PrivateClass1Closure = function () {var top = this;
function PrivateClass1 () {
this.myProperty=4;
}
PrivateClass1.prototype.callTopMethod = function () {
alert('My own myProperty is '+this.myProperty+', while the object above me has someProperty equal to '+top.constructorMethod()); // We can also get the latter value by top.someProperty
};
return PrivateClass1;
}; // Don't instantiate this closure yet

function Constructor () {
var _PrivateClass1 = _PrivateClass1Closure.call(this); // Let the closure have access to this context when generating the private class, so that its objects (the subobject below) can call the instance methods and properties of this nesting Constructor
this.subObject = new _PrivateClass1();
this.someProperty = 5;
}
Constructor.prototype.constructorMethod = function () {return this.someProperty;};
return Constructor;
}();

var obj = new Constructor();
obj.subObject.callTopMethod(); // My own myProperty is 4, while the object above me has someProperty equal to 5
alert(obj.constructorMethod()); // 5

0 Comments:

Post a Comment

<< Home


Google
 
Brett's Blog Web