Given the following code is it posible to access an object’s property from inside a “sub” object?
I imagine I’m doing this completely wrong, but I’m not sure what the right pattern to do is here. Any help would be much appreciated.
function MainObject(){
this.someProperty = "asdf";
return this;
}
MainObject.prototype.subClass = {};
MainObject.prototype.subClass.sayHi = function(){
// 'this' refers to the instance of MainObject.subClass
// How do I get to the instance's MainObject.someProperty property from here,
// without calling "widget.someProperty"?
};
widget = new MainObject();
You can’t since there is no reference to the actual instance. You’d have to initialize
subClassfor each instance inside the constructor:But that replicates functionality. It seems you should choose an other approach altogether.
Maybe using composition would be better, but that really depends on what you are trying to do and how the “classes” relate to each other.