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

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

    I've been playing around with this for the last 3 hours and finally got it at least somewhat elegant using new Function as suggested on other threads:

    /**
     * JavaScript Rename Function
     * @author Nate Ferrero
     * @license Public Domain
     * @date Apr 5th, 2014
     */
    var renameFunction = function (name, fn) {
        return (new Function("return function (call) { return function " + name +
            " () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
    };   
    
    /**
     * Test Code
     */
    var cls = renameFunction('Book', function (title) {
        this.title = title;
    });
    
    new cls('One Flew to Kill a Mockingbird');
    

    If you run the above code, you should see the following output to your console:

    Book {title: "One Flew to Kill a Mockingbird"}
    

提交回复
热议问题