控制台返回undefined

时间:2012-07-06 10:58:02

标签: javascript

所以我劫持了控制台功能

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

这具有所需的效果,但它也会将“未定义”作为意外奖励返回

我无法弄清楚为什么导致我认为这里有一些轻微的错误

enter image description here

Hello world由log.call(console, a)按预期生成

submitmsg()是我的自定义功能

这正是我想要的,正如我所说,虽然我稍微担心它也因为我不理解的原因而返回“未定义”。


注意: OP发布了以下代码作为问题的答案。对答案的评论已移至对该问题的评论。


所以正确的代码应该如下?

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

1 个答案:

答案 0 :(得分:11)

如果我正确理解了你的问题,那是因为你没有明确地从函数中返回任何东西。如果不从函数返回值,则会隐式返回undefined

例如:

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

这是在[[Call]] internal method specification(粗体相关点)中定义的:

  
      
  1. 让funcCtx成为使用F的[[FormalParameters]]内部值为函数代码建立新执行上下文的结果   property,传递的参数List args,以及此值为   在10.4.3中描述。
  2.   
  3. 让结果为评估作为F [[Code]]内部属性值的FunctionBody的结果。如果F没有   [[Code]]内部属性或者如果其值为空FunctionBody,   然后结果是(正常,未定义,空)。
  4.   
  5. 退出执行上下文funcCtx,恢复先前的执行上下文。
  6.   
  7. 如果result.type是throw,则抛出result.value。
  8.   
  9. 如果result.type为return,则返回result.value。
  10.   
  11. 否则result.type必须正常。返回undefined。
  12.   
相关问题