function.name - functionality

Posted on
  • Hello,
    Im looking to use Function.name in javascript. https://developer.mozilla.org/en-US/docs­/Web/JavaScript/Reference/Global_Objects­/Function/name
    while porting the Xstate library to Expruino.

    I believe Function.name or similiar is not available in Espruino.
    Also a common polyfill uses function.toString() and Although Espruino does have Object.toString() which operates on a function , the returned string does not provide the name. (see attached).

    Any thoughts on the possibility of implementing function.name or a workaround to get the name of a function ?
    Thanks in Advance


    2 Attachments

    • Function_Name2.JPG
    • Function_Name.JPG
  • Hmm, that's a tricky one - yes function.name isn't implemented. It's a bit tricky because to do it you'd end up having to waste a variable on every function to store the name twice. For instance this is what happens in Node:

    > var a = function() {}
    undefined
    > a.name
    'a'
    > var b = a;
    undefined
    > b.name
    'a'
    

    If all the functions you care about are in the global scope, you could run some code like this that adds name. It won't be fast but it'll work:

    function hello() {
    }
    
    Object.defineProperty(Function.prototype­, "name", {
      get : function(){
        for (var k in global)
          if (global[k] == this) return k;
      }});
    
    print(hello.name)
    
  • Thanks @Gordon,. I get the issue now with implementing.
    I appreciate your idea on the workaround and will try it out.

    Really enjoying working with Espruino , Pico is great, 5v tolerance really useful.
    Will be putting up on github, XState with Espruino including hierarchical states , asap.
    Comming along well.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

function.name - functionality

Posted by Avatar for SimonGAndrews @SimonGAndrews

Actions