473,324 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

get object name from within object

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'

Jul 23 '05 #1
17 31632


warteschlange wrote:
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.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
I guess that would be a problem for anonymous functions.

var myFunction=function(){};

Jul 23 '05 #3
Sorry, that was a statement of the obvious.

Jul 23 '05 #4
warteschlange wrote:
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.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #5
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.

Jul 23 '05 #6
VK


warteschlange wrote:
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>

Jul 23 '05 #7
VK wrote:
warteschlange wrote:
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>


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.

Jul 23 '05 #8
Matt Kruse wrote:
A good question is, "why?"
Christopher J. Hahn wrote: 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'
}
[/PHP]

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==

Jul 23 '05 #9
"VK" <sc**********@yahoo.com> writes:
warteschlange wrote:
is there a way to find out the object/function name from inside
object/function. function coffee(){
alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
}
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.

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

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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #10
Lasse Reichstein Nielsen wrote:
<snip>
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.
Jul 23 '05 #11
"Richard Cornford" <Ri*****@litotes.demon.co.uk> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #12
Lasse Reichstein Nielsen wrote:
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.

Jul 23 '05 #13
warteschlange wrote:
<snip>
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.
Jul 23 '05 #14
Richard Cornford wrote:
...
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

Jul 24 '05 #15
"warteschlange" <an****@holzapfel.ch> writes:
Richard Cornford wrote:
...


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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 24 '05 #16
warteschlange wrote:
Richard Cornford wrote: <snip> 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
don't remind me:
* this works only 'sync' and it can block the browser
* i know AJAX/XML_RPC/SOAP

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.

<snip> 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.
Jul 24 '05 #17
JRS: In article <dc*******************@news.demon.co.uk>, dated Sun, 24
Jul 2005 20:03:57, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
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 ... .

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 25 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: David Bear | last post by:
Let's say I have a list called, alist. If I pass alist to a function, how can I get the name of it? alist = range(10) def afunction(list): listName = list.__name__ (fails for a list object)
7
by: Brian Genisio | last post by:
Hi all, Does anyone know of a way in IE to determine the prototype name of an object? For instance, in Mozilla, I can say: junk = document.getElementById("myID"); alert(junk.toString());
1
by: Alex | last post by:
Is there a way to reference the "parent" object that creates a child object from within the child object? Or do I have to pass a reference to the parent object to the constructor of the child...
21
by: Gaemic | last post by:
Some argues that you should not use the C# keyword "object" instead of the real type System.Object. What would be the general rule of thumb for choosing one over the other? Thanks in advanced....
0
by: darrel | last post by:
I asked about this yesterday, but, alas, haven't made much headway. The situation: I have two SQL queries for deleting a record from my database. Each one deletes a record out of a different...
35
by: eyoung | last post by:
I call a function that takes the unit price and quantity ordered to create an amount...it looks something like this. function calculateCost() { quantity=document.RFO.quantity.value;...
3
by: ryanmhuc | last post by:
Is it possible to have a dynamic table name within a query or a table name that is a variable? This does not work but gives an example: SELECT * FROM concat('table', 'name') - OR - SET @table...
15
by: TonyV | last post by:
Hey all, for debugging purposes, I'd like to be able to access an object's instance name from within the object class. For example, I'd like to be able to do something like this: ...
23
by: Hugh Oxford | last post by:
How do I get an object's name? EG. $obj_FOO = new Bar; echo $obj_FOO->getName(); 'obj_FOO'
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.