Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
How to bind console.log to another function call so I can see line number of the script in console where it is called?

My code works but with additional parenthesis like myfunction()();. It should execute with single parenthesis just like normal e.g myfunction();.

I'm building console.time(); console.timeEnd(); polyfill for browsers (e.g <IE10) which do not have native built-in. Note: I have bind() polyfill in-case you think <IE10 does not have it.

Here is my code in "polyfill.js file".

(function() {
    'use strict';
    var console=window.console,  timers={};
    
    if (!console.time) {
        
        console.time = function(name) {
            var datenow = Date.now();
            name = name? name: 'default';
            if (timers[name]) {
                console.warn('Timer "'+name+'" already exists.');
            }
            else timers[name] = datenow;
        };
        
        console.timeEnd = function(name) {
            var datenow = Date.now();
            name = name? name: 'default';
            if (!timers[name]) {
                console.warn('Timer "'+name+'" does not exists.');
            }
            else {
                var endt = datenow - timers[name];
                delete timers[name];
                //below is the line where some changes are needed, But I don't know how.
                return window.console.log.bind(window.console, name+ ': ' +endt+ 'ms');
            }
        };
    }
}());

Now in another file "main.js file", when I use console.time(); console.timeEnd();, it should log code-line-number of this file in browser console (not the line-number of polyfill.js file). Of-course it works but notice additional parenthesis "()()" below which is not cool.

console.time();
//any code for performance test goes here.
console.timeEnd()(); //Note here "()()". It should be single "()"

I have consulted these 2 stackoverflow questions, but couldn't come up with the right answer.

  • Wrapping a wrapper of console log with correct file/line number?
  • A proper wrapper for console.log with correct line number?

I also checked new Error().stack; as an option, but it is also not supported in those browser for which I'm building my polyfill.

Note: If anyone can suggest a solution with eval();, you can. It is also acceptable for me.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There is in fact a function for that called console.trace, which you can read more about in the MDN page. What it does is print the entire stack trace to the line where it has been called from.

So, for example, running the next code:

function firstFunc() {
  secondFunc();
}

function secondFunc() {
  console.trace('I was called here!');
}

console.log('Calling firstFunc:');
firstFunc();

will print out this output in the console:

Calling firstFunc:

I was called here!
secondFunc @ VM141:6
firstFunc @ VM141:2
(anonymous) @ VM141:10 // Internal browser trace

Notice that in the given output, all functions are being called and defined in the Chrome console, hence the @ VM141:. Generally, it prints the file instead of VM. So, had it been located in an index.js file, it would look like this:

Calling firstFunc:

I was called here!
secondFunc @ index.js:8

Compatibility Note

The above method works for any sane browser, and IE11+. That is due to the implementation of console.trace only in IE11. However, per OP's request, I can think of a creative way to support IE10, and that is by using the Error.prototype.stack property. Now, of course, as MDN itself mentions it, it's a non-standard feature that should not be used in production, but neither is supporting IE6.

By creating an Error instance and then printing its stack, you can achieve a similar result.

const sumWithTrace = (num1, num2) => {
  console.log(new Error().stack); // Creating a new error for its stack property
  return num1 + num2;
};

sumWithTrace(1, 5); // returns 6 and prints trace in console
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda