8

So I've hijacked the console function:

var log = Function.prototype.bind.call(console.log, console);
console.log = function (a) {
    log.call(console, a);
    submitmsg("Log", a);
};

This has the desired effect. However, it also returns "undefined" as an unexpected bonus.

I can't figure out why which leads me to think there is something slightly wrong here.

Enter image description here

Hello world is generated by log.call(console, a) as expected

submitmsg() is my custom function

This is working exactly how I want. As I said though, I'm slightly concerned that it is also returning "undefined" for reasons I do not understand.


Note: The following code was posted by the OP as an answer to the question. The comments on the answer have been moved to the comments on the question.


So should the correct code be the following?

var log = Function.prototype.bind.call(console.log, console);
console.log = function (a) {
    return log.call(console, a);
    submitmsg("Log", a)
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

13

If I've understood your question correctly, it's because you are not explicitly returning anything from the function. When you don't return a value from a function, it implicitly returns undefined.

For example:

function example() {}
console.log(example()); //undefined

This is defined in the [[Call]] internal method specification (relevant points in bold):

  1. Let funcCtx be the result of establishing a new execution context for function code using the value of F's [[FormalParameters]] internal property, the passed arguments List args, and the this value as described in 10.4.3.
  2. Let result be the result of evaluating the FunctionBody that is the value of F's [[Code]] internal property. If F does not have a [[Code]] internal property or if its value is an empty FunctionBody, then result is (normal, undefined, empty).
  3. Exit the execution context funcCtx, restoring the previous execution context.
  4. If result.type is throw then throw result.value.
  5. If result.type is return then return result.value.
  6. Otherwise result.type must be normal. Return undefined.
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Hi James, i did start there, however that functionality overrides the console's output not add to it, although your answer is correct it would not actually output to the console –  Jul 06 '12 at 11:07
  • @Fibrewire - What are you expecting to be returned? The native `console.log` method returns `undefined`, so I don't see the problem. – James Allardice Jul 06 '12 at 11:12
  • Latest link as of 2022: https://262.ecma-international.org/12.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist – wlnirvana Mar 30 '22 at 06:24