Consider the Following Example
var Foo = function(){
this.identity = 'Foo';
};
Foo.prototype.bar = function(){
this.identity = 'bar';
};
var fooInstance = new Foo(),
bar = new fooInstance.bar();
Question
Within bar
, how may I obtain the fooInstance
variable? Is there a way for a child of Foo
to recognize its parent as fooInstance
? For example, how could I create a function in bar
that would return fooInstance
. A slight caveat is that bar must by created using the prototype
command and cannot simply be nested in Foo
to access any Foo
instances that way.
My Ideas and Why They Don't Work
It would be possible to rewrite the functions like so
var Foo = function(){
this.identity = 'Foo';
};
Foo.prototype.createBar = function(){
var parent = this;
function bar(){
this.parent = parent;
this.identity = 'bar';
};
return new bar();
};
var fooInstance = new Foo(),
bar = fooInstance.createBar();
Yet for the purposes of creating easily readable code i would rather not use this approach if not needed.
Further Clarification
Let me put the question in context. I am prototyping on CanvasRenderingContext2D so that all contexts for the canvas element will contain my new method. Lets call that method foo and assume context is a created canvas context. How create a variable like so "new context.foo()" such that the foo function can use the context variable?