get object name from within object

W

warteschlange

is there a way to find out the object/function name from inside
object/function.

function coffee(){
alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
}

var milk = new coffee(); => should give me 'milk'
 
M

Martin Honnen

warteschlange said:
is there a way to find out the object/function name from inside
object/function.

Inside of a function you can access
arguments.callee
which is the function called. With Mozilla JavaScript functions have a
name property so there you can access
arguments.callee.name
to get the function name but other browsers/implementations do not
implement that name property so there if you need the function name you
would need to try to parse it out of the function's source code
representation, i.e. you need to parse
arguments.callee.toString()
for the function name.
 
B

Baconbutty

I guess that would be a problem for anonymous functions.

var myFunction=function(){};
 
M

Matt Kruse

warteschlange said:
is there a way to find out the object/function name from inside
object/function.
function coffee(){
alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
}
var milk = new coffee(); => should give me 'milk'

A good question is, "why?"

Perhaps there is a better way to do what you're trying to do without needing
this functionality.
 
L

Lee

warteschlange said:
is there a way to find out the object/function name from inside
object/function.

function coffee(){
alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
}

var milk = new coffee(); => should give me 'milk'

In your last line, the variable "milk" may not even exist at
the time that the function is executing.

The Object that is created is completely distinct from any
variable that contains a reference to it. The Object doesn't
have any intrinsic name. Any number of named variables may
hold references to the Object.
 
V

VK

warteschlange said:
is there a way to find out the object/function name from inside
object/function.

function coffee(){
alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
}

var milk = new coffee(); => should give me 'milk'

Quick'N'Durty (RegExp, constructor chain and so are welcome):

<script type="text/javascript">

function FunctionOne() {
FunctionTwo();
}

function FunctionTwo() {
var s = '';
if (arguments.callee) {
var thisName = getObjectName(arguments.callee);
s+= "My name is " + thisName;
}
if (arguments.caller) {
s+= "\nI'm called by ";
s+= getObjectName(eval(thisName+".caller"));
}
alert(s);
}

function getObjectName(obj) {
var tmp = obj.toString();
return tmp.substring(tmp.indexOf(' ')+1,tmp.indexOf('('));
}
</script>
 
C

Christopher J. Hahn

VK said:
Quick'N'Durty (RegExp, constructor chain and so are welcome):

<script type="text/javascript">

function FunctionOne() {
FunctionTwo();
}

function FunctionTwo() {
var s = '';
if (arguments.callee) {
var thisName = getObjectName(arguments.callee);
s+= "My name is " + thisName;
}
if (arguments.caller) {
s+= "\nI'm called by ";
s+= getObjectName(eval(thisName+".caller"));
}
alert(s);
}

function getObjectName(obj) {
var tmp = obj.toString();
return tmp.substring(tmp.indexOf(' ')+1,tmp.indexOf('('));
}
</script>

You're trying to get the object's constructor's name (coffee, in this
case), (and doing it badly, besides), but I gather what the OP wants is
the name of the variable containing the reference to the object (milk,
in this case).

Part of the problem is I'm pretty sure is that milk doesn't yet exist
at the time that coffee is called.

In 'milk = new coffee()', I'm *fairly* sure that coffee() is called
first, then = works its magic to autovivify it if necessary, et cetera,
then actually does the assignment.

All of that is better explained (or debunked entirely) by a real expert
on the language.

One way to workaround might be to say
milk = new coffee( 'milk' );
but that's not really what the OP wants.


The other problem is here:
milk = new coffee( 'milk' );
sugar = milk;

sugar and milk now reference to the same object, but the object thinks
it's milk. It doesn't know about sugar.

milk = new coffee( 'milk' );
sugar = milk;
milk = new coffee( 'milk' );

and now two objects think they are milk, when one of them is really
sugar. sugar thinks it's milk, and if it tries to operate on what it
thinks itself really is, it'll actually be operating on milk.

I don't believe that it's possible (or possibly adviseable) to do what
the OP is after, but maybe if we understood why he wanted to do it, we
could suggest another way to achieve the ultimate end goal.
 
W

warteschlange

Matt said:
A good question is, "why?"
but maybe if we understood why he wanted to do it, we
could suggest another way to achieve the ultimate end goal.


ok,
I will explain the reason '''why''' with an example of a function,
(leaving beside php-classes/ js-object)

what i do is a js2php interface
so i can use all my php functions directly from javascript.
this works perfectly so far.

var jsVar = trulyPHPFunc( args);
The point is, that i have to hardcode for each function its name as
parameter
because i create all javascript functions dynamically as a 'mirror' of
my phpfunctions/classes
and don't know the name during creation.

for example:

i have a php function/class
PHP:
function trulyPHPFunc( arguments ){
return 'someStuff'
}

i create dynamic a jsfunction
[JS]
function trulyPHPFunc( arguments ){
return call_HTTP_Request( {func:callee , args:arguments } );
// where calle is the name
}
[/JS]

don't remind me:
* this works only 'sync' and it can block the browser
* i know AJAX/XML_RPC/SOAP
* and no, there is no security leak

In a intranet it is like heaven to write apps.
no longer need to 'submit' the classic way,
just onchange='doPHPfunc(this)'

==use the best of both worlds==
 
L

Lasse Reichstein Nielsen

Possible, but why bother when you can just use the string "coffee",
because the code to find the name will be inside the function with the
declared name "coffee" anyway. Ofcourse, just using a string violates
the DRY principle (Don't Repeat Yourself), but the alternatives are
not as well supported.
Impossible.

....
var thisName = getObjectName(arguments.callee);

Here you find the name of arguments.callee ...
if (arguments.caller) {
s+= "\nI'm called by ";
s+= getObjectName(eval(thisName+".caller"));

and here you look that name up. As usual, the use of eval is
not necessary, just use the value directly:
s+= getObjectName(arguments.callee.caller);

However, since you guard this with
if (arguments.caller) {
you might mean to do just
s+= getObjectName(arguments.caller);

In any case, arguments.caller and func.caller are not part of the
ECMAScript standard, and is not implemented in all browsers.
function getObjectName(obj) {
var tmp = obj.toString();
return tmp.substring(tmp.indexOf(' ')+1,tmp.indexOf('('));

This can error if the obj is a function from a function expression,
see, e.g.,
alert((function(){alert("goo");}).toString())


Still, arguments.callee is the only way to access the current function
without knowing its name. It's just that it only works inside that function,
and at that point, you should know the name.
/L
 
R

Richard Cornford

Lasse Reichstein Nielsen wrote:
Still, arguments.callee is the only way to access the
current function without knowing its name. It's just that
it only works inside that function, and at that point,
you should know the name.

Which means that the only circumstances where arguments.callee would be
necessary is when the function is anonymous (the result of an anonymous
function expression or the use of the Function constructor, but only
sometimes), or when the author has (rather stupidly) re-used the
function's name as a formal parameter, local variable or inner function
name and so masked the property on the scope chain that refers to the
function itself.

Richard.
 
L

Lasse Reichstein Nielsen

Richard Cornford said:
Which means that the only circumstances where arguments.callee would be
necessary is when the function is anonymous (the result of an anonymous
function expression or the use of the Function constructor, but only
sometimes),

.... in which case there is no name to find ...
or when the author has (rather stupidly)

(probably why I didn't even consider it :)
re-used the function's name as a formal parameter, local variable or
inner function name and so masked the property on the scope chain
that refers to the function itself.

But still, the original poster's question went to the name of the
function, not the function itself, so going through "callee" is
more work than is normally needed.

I would pass the function name as a parameter to the PHP function that
generates the JS function. It's much safer than trying to deduce it on
the client.

/L
 
W

warteschlange

Lasse said:
I would pass the function name as a parameter to the PHP function that
generates the JS function. It's much safer than trying to deduce it on
the client.
after thinking over it and a few cup of coffee later , i will keep it
straight and make it from PHP.
thanks to all in the jsOlymp lowering my coffee consumption.
I mean it honestly - js can be hell without help.
 
R

Richard Cornford

warteschlange wrote:
i create dynamic a jsfunction
[JS]
function trulyPHPFunc( arguments ){
return call_HTTP_Request( {func:callee , args:arguments } );
// where calle is the name
}
[/JS]

But when you dynamically create this function you must know its name in
order to output ' function trulyPHPFunc( ... ', so what is stopping you
dynamically inserting the same function name into a string within the
function?
don't remind me:
* this works only 'sync' and it can block the browser

It is not 'can block the browser', it is 'will block the browser'.
Blocking the browser is a bad idea that should be avoided. It is
particularly problematic when the network or server experience problems
as it blocks the browser until the request times out.
* i know AJAX/XML_RPC/SOAP

The statement 'I know AJAX' seems somewhat vague. The 'A' in AJAX stands
for asynchronous so to 'know' AJAX should be to know how to handle
asynchronous background client-server interactions. Granted the term
'AJAX' appears to have been degraded to mean nothing more than using
HTTP request objects, and then quite often synchronously because the
thought and effort involved in coping with asynchronous operations
exceeds the willingness or the knowledge of those interested in applying
a buzzword to their own creations.

Richard.
 
W

warteschlange

Richard said:

what you are saying in other words: keep javascript clean and do all
the crap on the php side.

My aproach was sending a list of functions from php to javascript,
allowed to use. Just a list (getMethods() ) as usual in xml_rpc. This
is an array of strings.
And: if i have a nice working backend, why writing another interface?

So the original question was: how to get a function, with its name as
argument, from a string.
Hey, why not use eval? Answer: I don't like eval at all.
I try to keep it simple and avoid the xml_rpc/soap overhead.

I got all the good answers very quick and came to the conclusion, that
it is easier to solve it in php with a wrapper. But now i'm spending my
time chatting around justifying my aproach.

Just asking a good question and not explaining all the background, does
not automatically mean, that he/she is not aware of the rest. I
thought, pointing out
don't remind me:
* this works only 'sync' and it can block the browser
* i know AJAX/XML_RPC/SOAP
will avoid a discussion about these items.

But i was wrong.

So why not introduce a syntax in the discussons for marking out items
not to be discussed?
example:
my son (9) want to see '''Once upon a time in Mexico'''
question: are there any sequences of violence?
[avoid_topics_in_this_thread]
quality of the movie
why Rodriquez filmed in HDTV
beauty of Hayek, Mendes
[/avoid_topics_in_this_thread]

this will help to focus.

Sync is not a bad idea, it is just bad implemented in the browsers.
(Other languages have a lot better mechanism to fetch a result from a
function without blocking the rest, if needed : vb/c++/j++ ).
[avoid_topics_in_this_thread]
sync/async
[avoid_topics_in_this_thread]


Andres Obrero
 
L

Lasse Reichstein Nielsen

warteschlange said:
what you are saying in other words: keep javascript clean and do all
the crap on the php side.

I concur. You have *full* control of the PHP code and environment,
whereas anything in a web page can be changed by proxies and user
preferences, and will be running in one of a dozen browsers with
slightly-to-greatly different runtime environments.

/L
 
R

Richard Cornford

warteschlange said:
Richard Cornford wrote:
I got all the good answers very quick and came to the
conclusion, that it is easier to solve it in php with a
wrapper. But now i'm spending my time chatting around
justifying my aproach.

Any suggestion of an interest in the names of functions (and
particularly variables that refer to objects and object instances (which
may be functions)) raises the suspicion that the underlying code is
fundamentally flawed in its design. And that a simpler, clearer (often
faster) and more direct alternative could be suggested in exchange for a
sufficient explanation of the problem context.
Just asking a good question and not explaining all the
background, does not automatically mean, that he/she is
not aware of the rest.

Many people assert that they know and understand what they are doing,
while simultaneously making demands/request/assumptions that suggest
that they do not. And when they bother to engage to the point of
allowing others to actually understand what is being done it more often
as not turns out that they were unaware of something significant (and
often advantageous).
I thought, pointing out

You realise that you have attributed that quote to me when you are its
author and not me.
will avoid a discussion about these items.

But i was wrong.

So why not introduce a syntax in the discussons for
marking out items not to be discussed?

Because nobody would pay any attention to it at all.

Sync is not a bad idea, it is just bad implemented
in the browsers.

In an event driven system there is no need to block, so doing so is a
bad idea. But when blocking is known to block _everything_ (even if it
doesn't strictly have to) it should be a more obviously bad idea.
(Other languages have a lot better mechanism to fetch a
result from a function without blocking the rest, if
needed : vb/c++/j++ ).
<snip>

And web browsers have completely viable mechanisms for allowing code to
react to events (including onreadystatechange on XML HTTP Request
objects) and javascript has mechanisms for preserving contexts between
the initiation of requests and the events following the response. So the
extent to which it is necessary to block is extremely questionable.

Richard.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Sun, 24
Jul 2005 20:03:57, seen in Richard Cornford
Any suggestion of an interest in the names of functions (and
particularly variables that refer to objects and object instances (which
may be functions)) raises the suspicion that the underlying code is
fundamentally flawed in its design.

Possibly.

I have a function which, given a variable that addresses a function,
returns the original name of the function. At least, it does for me; I
don't see any reason for it not to work generally. As I use it,
function execution time is not important.

function Primordial() {}
var B = Primordial, C = B, D = FuncName(C)

Variable D is now a String of value " Primordial" (I always either want
the space or don't mind it).

function FuncName(Fn) { return Fn.toString().match(/( \w+)/)[0] }


It's useful in test code; a test routine can be given the function to
test, and use FuncName to discover the its name as a string for display.
Otherwise, one would either pass both the variable and the corresponding
name-string, or pass the name-string and use eval ... .
 

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,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top