2012-07-06 79 views
6

所以IVE劫持控制台功能控制台返回undefined

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

这有预期的效果但是它也返回“未定义”作为一个意想不到的好处

我无法弄清楚,为什么这使我觉得有东西稍微错在这里

enter image description here

你好由log.call(console, a)产生世界预计

submitmsg()是我的自定义功能

这是工作正是我想要的,正如我所说的,虽然IM略有担心,它也返回的原因,我不明白“不确定”。


注:下面的代码被张贴在OP作为一个问题的答案。关于答案的评论已转移到对这个问题的评论。


所以正确的代码应该是以下内容?

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

这仍然还返回 “未定义” – Fibrewire 2012-07-06 11:16:54

+0

这是因为'log.call'返回'undefined'。这就是为什么我不确定你想要达到什么样的效果......原生的控制台。log'方法返回'undefined'。你想要返回什么? – 2012-07-06 11:18:45

+0

对不起,我已经更详细地提交了 – Fibrewire 2012-07-06 11:29:05

回答

10

如果我正确地理解了你的问题,那是因为你没有明确地从函数返回任何东西。当你不从函数返回一个值时,它隐含地返回undefined

例如:

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

这在[[Call]] internal method specification(粗体相关点)之一定义:

  1. 设funcCtx是使用建立功能代码新的执行上下文的结果F的[[FormalParameters]]内部 属性的值,传递的参数List args和此值在10.4.3中描述的 。
  2. 让结果成为评估F的[[Code]]内部属性值的FunctionBody的结果。如果F没有 [[Code]]内部属性,或者其值为空函数体,则 的结果为(正常,未定义,为空)。
  3. 退出执行上下文funcCtx,恢复上一个执行上下文。
  4. 如果result.type被抛出然后抛出result.value。
  5. 如果result.type返回,则返回result.value。
  6. 否则result.type必须正常。返回undefined。
+0

嗨James, 我确实从那里开始,但是该功能会覆盖控制台的输出而不是添加到它,虽然你的答案是正确的,它不会实际输出到控制台 – Fibrewire 2012-07-06 11:07:56

+0

@Fibrewire - 你期待什么被返回?原生的'console.log'方法返回'undefined',所以我没有看到问题。 – 2012-07-06 11:12:26