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

前端 未结 11 1483
萌比男神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

    Although it is ugly, you could cheat via eval():

    function copy(parent, name){
      name = typeof name==='undefined'?'Foobar':name;
      var f = eval('function '+name+'(){};'+name);
      f.prototype = parent;
      return new f();
    }
    
    var parent = {a:50};
    var child = copy(parent, 'MyName');
    console.log(child); // Shows 'MyName' in Chrome console.
    

    Beware: You can only use names which would be valid as function names!

    Addendum: To avoid evaling on every object instantiation, use a cache:

    function Cache(fallback){
      var cache = {};
    
      this.get = function(id){
        if (!cache.hasOwnProperty(id)){
          cache[id] = fallback.apply(null, Array.prototype.slice.call(arguments, 1));
        }
        return cache[id];
      }
    }
    
    var copy = (function(){
      var cache = new Cache(createPrototypedFunction);
    
      function createPrototypedFunction(parent, name){
        var f = eval('function '+name+'(){};'+name);
        f.prototype = parent;
        return f;
      }
    
      return function(parent, name){
        return new (cache.get(name, parent, typeof name==='undefined'?'Foobar':name));
      };
    })();
    

提交回复
热议问题