[英]Javascript Object Constructor get variable name that called constuctor
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. 从CS_Sidekick构造函数内部,可以通过任何方式找出调用该构造函数的变量,在这种情况下,我想获取foo。
So something like 所以像
function CS_Sidekick(){
//return foo since that's the variable that called it
}
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. 从CS_Sidekick构造函数内部,可以通过任何方式找出调用该构造函数的变量,在这种情况下,我想获取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. CS_Sidekick()
构造函数不知道调用代码将如何处理结果新实例。
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
. 当CS_Sidekick()
运行时,尚未设置foo
的值,因此CS_Sidekick()
尝试返回foo
确实没有任何意义。 foo
doesn't yet have a value. foo
还没有任何价值。 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()
. 是为变量foo
分配一个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. 应该返回CS_Sidekick
对象的新实例。 That's what it should do. 那是应该做的。
PS 聚苯乙烯
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. 如果您想让CS_Sidekick()
构造函数知道有关其调用方的信息,则可以将其作为参数传递给构造函数。 There is no automatic way to retrieve information about the calling environment from within the constructor. 没有自动方法可以从构造函数中检索有关调用环境的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.