Reputation: 13
This is probably not possible but i need to ask anyway.
if i have a constructor function something like:
function CS_Sidekick() {
//do whatever
}
var foo = new CS_Sidekick();
From inside the CS_Sidekick constructor is there any way to figure out the variable that called the constructor, in this case i'd like to get foo.
So something like
function CS_Sidekick(){
//return foo since that's the variable that called it
}
Upvotes: 0
Views: 242
Reputation: 708206
From inside the CS_Sidekick constructor is there any way to figure out the variable that called the constructor, in this case i'd like to get foo.
No, there is not. The CS_Sidekick()
constructor has no idea what the calling code is going to do with the resulting new instance.
You really need to describe what problem you're actually trying to solve because your comments here make no sense:
function CS_Sidekick(){
//return foo since that's the variable that called it
}
When there is code like this:
var foo = new CS_Sidekick();
The value of foo
is not yet set when CS_Sidekick()
runs so it really makes no sense for CS_Sidekick()
to try to return foo
. foo
doesn't yet have a value. Besides, the whole point of the callers code:
var foo = new CS_Sidekick();
is to assign the variable foo
a new instance of CS_Sidekick()
. If that's not what the caller wants, then the caller needs to change their code to something else.
new CS_Sidekick();
should return a new instance of the CS_Sidekick
object. That's what it should do.
P.S.
If you want the CS_Sidekick()
constructor to know something about it's caller, then you can pass that into the constructor as an argument. There is no automatic way to retrieve information about the calling environment from within the constructor.
Upvotes: 2