Here's an example constructor
function AnObject(a, b){
this.a = a;
this.b = b;
}
and an instantiation of it
var example = new AnObject('test', 'test');
Lets say that the constructor had a property .name
is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?
In the case above, the name would be example
-EDIT-
The reason I am trying to achieve this is to be as "D.R.Y" as possible.
I would like to NOT have to:
var example = new ObjectWithName('example');
No. I'm afraid that's not possible!
You see, the statement var example = new AnObject('test', 'test');
is evaluated from right to left. So, first new AnObject('test', 'test')
is evaluated. Then, the value it returns is assigned to var example
.
Because of this right-to-left evaluation, there is no way your AnObject
constructor can know that its return value is going to be assigned to variable example
when it's being evaluated.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments