get object name from within object

Discussion in 'Javascript' started by warteschlange, Jul 22, 2005.

  1. 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'
    warteschlange, Jul 22, 2005
    #1
    1. Advertising

  2. 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/
    Martin Honnen, Jul 22, 2005
    #2
    1. Advertising

  3. warteschlange

    Baconbutty Guest

    I guess that would be a problem for anonymous functions.

    var myFunction=function(){};
    Baconbutty, Jul 22, 2005
    #3
  4. warteschlange

    Baconbutty Guest

    Sorry, that was a statement of the obvious.
    Baconbutty, Jul 22, 2005
    #4
  5. warteschlange

    Matt Kruse Guest

    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
    Matt Kruse, Jul 22, 2005
    #5
  6. warteschlange

    Lee Guest

    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.
    Lee, Jul 22, 2005
    #6
  7. warteschlange

    VK Guest

    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>
    VK, Jul 23, 2005
    #7
  8. 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.
    Christopher J. Hahn, Jul 23, 2005
    #8
  9. 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 trulyPHPFuncarguments ){
    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==
    warteschlange, Jul 23, 2005
    #9
  10. "VK" <> 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 -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 23, 2005
    #10
  11. 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.
    Richard Cornford, Jul 23, 2005
    #11
  12. "Richard Cornford" <> 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 -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 23, 2005
    #12
  13. 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.
    warteschlange, Jul 23, 2005
    #13
  14. 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.
    Richard Cornford, Jul 23, 2005
    #14
  15. 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
    warteschlange, Jul 24, 2005
    #15
  16. "warteschlange" <> 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 -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 24, 2005
    #16
  17. 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.
    Richard Cornford, Jul 24, 2005
    #17
  18. JRS: In article <dc0omu$4hr$1$>, dated Sun, 24
    Jul 2005 20:03:57, seen in news:comp.lang.javascript, Richard Cornford
    <> 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.
    Dr John Stockton, Jul 25, 2005
    #18
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?iso-8859-1?B?bW9vcJk=?=
    Replies:
    7
    Views:
    809
    Roedy Green
    Jan 2, 2006
  2. ding feng
    Replies:
    2
    Views:
    2,789
    ding feng
    Jun 25, 2003
  3. Bobby Chamness
    Replies:
    2
    Views:
    2,379
    Joe Smith
    Apr 22, 2007
  4. Jack-2
    Replies:
    3
    Views:
    255
    Jack-2
    Dec 24, 2003
  5. Martin
    Replies:
    6
    Views:
    172
    Richard Cornford
    Aug 20, 2004
Loading...

Share This Page