How to safely wrap `console.log`?

后端 未结 10 505
日久生厌
日久生厌 2021-01-31 14:13

Suppose I want to include some calls to console.log for some legitimate production reason, say for something like a unit test harness. Obviously I would not want th

10条回答
  •  生来不讨喜
    2021-01-31 14:57

    Can this log function be called normally on IE, and the use of apply here is just to show it's possible?

    Yes, and yes. That particular example was aimed squarely at the "is it a real function" part of the linked question.

    And, I assume from the linked question that this will fail if IE's console is closed when it runs, so log won't work even after the console opens, correct?

    Correct. As explained in my answer on that question, the console object is not exposed until the first time the developer tools are opened for a particular tab. Most developers use a console shim, in which case the Function#bind approach becomes a little obsolete because you may as well use the Function#apply.apply method.

    What is the purpose of converting arguments to an array in this case?

    There isn't one, it's redundant. Unless it's a custom log implementation, in which case the developer may have a reason to convert an arguments object to an array.

    And does prototype serve a purpose in the above examples, or are we just being pedantic...

    Well, yes and no. Some developer may have unwittingly changed Function.call to a custom function or value. Of course, they could break Function.prototype.call too, but this is far less likely to happen by accident.

提交回复
热议问题