Reputation: 892
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');
Upvotes: 0
Views: 39
Reputation: 47101
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.
Upvotes: 1
Reputation: 9365
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?
When you create a new object with
new AnObject('test', 'test')
this results in an object reference, which can be then just used directly:
(new AnObject("test","test")).a
or discarded
new AnObject('test', 'test')
or assigned to some other object property:
myotherobject["b"]=new AnObject('test', 'test')
or pushed into an array:
myarr.push(new AnObject('test', 'test'))
or assigned to multiple variables at once
a=b=c=d=e = new AnObject('test', 'test');
and there is no way your constructor can know in which way the object (reference) will be used, or know the name of the variable it will be assigned to (in case of simple variable assignment).
In other words creating an object and doing something with the resulting object reference are two completely independent actions.
So unless you explicitly pass the "name" value into the constructor as the argument:
var example = new AnObject('example','test','test')
or set it later on
example.name="example"
there is no way you can achieve that.
Upvotes: 1