I have a class that I want to extend with a couple of new methods.
In order not to pollute the object's namespace (possible overwrite of existing methods) more than necessary I want to group these methods under one property name.
How can I get a reference for the original object's instance inside of the extended container?
To clarify:
// here's what I have
obj = function () {
// something happens here
this.property = "XYZ"
}
var x = new obj();
console.log(x.property); // logs "XYZ"
// here's how I want to extend it
obj.prototype.extension = {property: "ABC"};
obj.prototype.extension.whatstheproperty = function () {
// how to get a reference to the obj's instance here?
console.log(this.property); // logs "ABC" not "XYZ" for obvious reasons
// QUESTION -> how get get "XYZ"?
}
var z = new obj();
z.extension.whatstheproperty();
My guess is there must be a way to store a reference to the parent instance as a property of extension
.
An obvious way would be to just set it whenever the parent is instanced:
x = new obj();
x.extension.parent = x;
Then I could access this.parent
inside all methods of extension
.
But I feel there must be a better way, especially because I don't know when a new obj
is instanced.
I just want every new obj to have a property extension
that has a property referencing the parent instance.
How should I approach this?