3 Replies Latest reply on Oct 16, 2008 1:28 AM by srakete

    JS: name of current function

    srakete Level 1
      Hi,
      I am using JavaScript and for logging puposes I would like to write the current function/method to my error log. I have looked into reflection but so far without success.
      Thanks for help
      Stefan
        • 1. Re: JS: name of current function
          Level 1
          I've never tried anything like this, but this experiment brings some hope. I ran this in ESTK:

          function fred() {
          for (var j in this) {
          alert(j);
          }
          }

          fred();

          and the last value of j was "fred" -- hope this helps.

          Dave
          • 2. Re: JS: name of current function
            Level 1
            > I am using JavaScript and for logging puposes I would like to write the current function/method to my error log. I have looked into reflection but so far without success.

            Here's some code that shows a couple of different ways of getting the function
            name for both functions and methods.

            Using the $.stack.split technique is probably the preferred way of doing this
            since it gives you a name for the function even if it's literal assigned to a
            variable.

            Plus, you could use it inside of your log function. Take the array returned by
            split and the second to the last entry is the name of the function that called
            your log function. That reduces the clutter in the functions that you are trace
            logging.


            -X



            function test() {
            $.writeln($.stack.split(/[\n]/).pop());
            $.writeln(arguments.callee.name);
            }

            function test2() {
            test();
            }
            test2();

            function Test() {};

            Test.prototype.ftn0 = function() {
            $.writeln($.stack.split(/[\n]/).pop());
            $.writeln(arguments.callee.name);
            }

            Test.prototype.ftn1 = function xxx() {
            $.writeln($.stack.split(/[\n]/).pop());
            $.writeln(arguments.callee.name);
            }
            Test.prototype.ftn2 = function() {
            this.ftn0();
            this.ftn1();
            }

            var t = new Test();
            t.ftn2();



            ========== Output in ESTK ========
            test()
            test
            ftn0()
            anonymous
            xxx()
            xxx
            • 3. Re: JS: name of current function
              srakete Level 1
              Thanks. That was what I was looking for. Stefan