Why can't I expand this event object in the chrome console?

前端 未结 4 2182
情深已故
情深已故 2021-01-01 16:54

Simplified, what I\'m doing is running this in the console:

window.onbeforeunload = function (e) {
    console.log(e);
}

But in the console

4条回答
  •  春和景丽
    2021-01-01 17:15

    It's a good practice when inspecting objects or arrays that can change later to drop in a

    debugger
    

    ...after the point in the code you want to debug. This pauses the execution of the code at this point and means you know for sure you're seeing its state at this point, rather than any subsequent changes.

    The failure to expand can mean that the object was subsequently deleted or garbage-collected, or (especially if you're using Chrome dev tools on a Node.js script) that the script is complete, so all refs point nowhere.


    In fact, an arguably better practice is to use debugger instead of console.log, then find what you want to inspect in the local variables.

    window.onbeforeunload = function (e) {
      debugger; // Now go find `e` in the local variables section
    }
    

    Also, always remember that in Javascript any time you deal with a variable that points to an object, you're dealing with a live reference, to the latest state of that object. So, console.log logs the reference, not the object contents, and when you view and expand the logged reference, you're viewing what that reference points to at the time you look at it, not the time you logged it. This might be nothing if it has been removed from memory or reassigned.

    Variables pointing to strings and numbers point to values not references, so another option might be to log a stringified version of the object, like console.log(JSON.stringify(someObject)) (although that output may be harder to read). The debugger approach is usually better.

提交回复
热议问题