How to dynamically set a function/object name in Javascript as it is displayed in Chrome

前端 未结 11 1484
萌比男神i
萌比男神i 2020-11-28 07:21

This is something which has been bugging me with the Google Chrome debugger and I was wondering if there was a way to solve it.

I\'m working on a large Javascript ap

11条回答
  •  甜味超标
    2020-11-28 08:01

    I think this is the best way to dynamically set the name of a function :

       Function.prototype.setName = function (newName) {
           Object.defineProperty(this,'name', {
              get : function () { 
                  return newName; 
              }
           });
        }
    

    Now you just need to call the setName method

    function foo () { }
    foo.name; // returns 'foo'
    
    foo.setName('bar');
    foo.name; // returns 'bar'
    
    foo.name = 'something else';
    foo.name; // returns 'bar'
    
    foo.setName({bar : 123});
    foo.name; // returns {bar : 123}
    

提交回复
热议问题