Javascript: console log uses parent scope

Is it possible to use some javascript tricks to tell console.logthe line number that it should output?

Suppose we have the following simple example:

function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg
        console.log(msg);
    };
}

var log = new Logger();
log.debug("Hello");

If you open the page, Chrome shows this:

enter image description here

This means that the message has been logged on main.js:4, but I really want it to show main.js:9. Because line 9 is where the registrar is called. For this simple case, this does not really matter, but when Logger is in a separate file, it always shows logger.jsinstead of the class that the registrar called.

Logger (, ), this.debug = console.log.

EDIT:

, , :

+4
1

, , - Error , , , :

function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg

        //TODO: document this line
        var callerLine = new Error().stack.split('\n')[2];
        console.log(msg, callerLine);
    };
}

var log = new Logger();
log.debug("Hello");

( ).

+1

All Articles