Can a JavaScript object get its own name ?

A

Aaron Gray

Given :-

function Test( v1, v2)
{
this.V1 = v1;
this.V2 = v2;
}

var t = new Test( "x", "y");

Besides making "x" "t" is there anyway that t can get its own name, not the
class name but its own name ?

AFAICT there is no way to do this other than to pass its own name through
as a parameter.

Aaron
 
R

RobG

Aaron said:
Given :-

function Test( v1, v2)
{
this.V1 = v1;
this.V2 = v2;
}

var t = new Test( "x", "y");

Besides making "x" "t" is there anyway that t can get its own name, not the
class name but its own name ?

No, and it is generally of no use to do so because you can have
multiple references to the same object and the 'name' itself only has
meaning within a particular context (scope). Consider:

var t = new Test();
var x = t;

Now t has two 'names'. Then:

t = null;

Now the object formerly referred to as t can only be referred to as x.
Also:

var tObj = { t : new Test() };

The 'name' of the new object is t, however it can only be accessed from
tObj.

AFAICT there is no way to do this other than to pass its own name through
as a parameter.

Correct, but then name is just a property of the object and not of much
use for accessing it. If you want a reference to a function object
from within the function, say so it can call itself, then use
arguments.callee, or give the object a 'self' property:

function Test() {
this.self = this;
}

var t = new Test();
alert( t == t.self );


Either way, you still don't get the 'name' - although some browsers
support callee.name.
 
A

Aaron Gray

No, and it is generally of no use to do so because you can have
multiple references to the same object and the 'name' itself only has
meaning within a particular context (scope). Consider:

Right just checking.
Correct, but then name is just a property of the object and not of much
use for accessing it. If you want a reference to a function object
from within the function, say so it can call itself, then use
arguments.callee, or give the object a 'self' property:

function Test() {
this.self = this;
}

var t = new Test();
alert( t == t.self );


Either way, you still don't get the 'name' - although some browsers
support callee.name.

Closures seem the way to solve my original problem.

Thanks,

Aaron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top