【问题标题】:Console returns undefined [duplicate]控制台返回未定义 [重复]
【发布时间】:2012-07-06 20:03:38
【问题描述】:

所以我劫持了控制台功能:

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

这达到了预期的效果。但是,它也会返回“未定义”作为意外奖励。

我不明白为什么这导致我认为这里有一些小问题。

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

submitmsg() 是我的自定义函数

这正是我想要的。不过,正如我所说,我有点担心由于我不明白的原因它也会返回“未定义”。


注意: OP 发布了以下代码作为问题的答案。答案上的 cmets 已移至问题上的 cmets。


那么正确的代码应该如下吗?

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

【问题讨论】:

  • 这仍然返回“未定义”
  • 那是因为log.call 返回undefined。这就是为什么我不确定您要达到什么目的......本机console.log 方法返回undefined。你想返回什么?
  • 对不起,我重新提交了更详细的内容
  • 在您编辑问题后,如果我调用真正的 console.log 方法,我会在控制台中得到完全相同的结果。那是因为console.log 返回undefined
  • 现在submitmsg 根本不起作用,是故意的吗?

标签: javascript


【解决方案1】:

如果我正确理解了您的问题,那是因为您没有明确地从函数中返回任何内容。当您不从函数返回值时,它会隐式返回 undefined

例如:

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

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

  1. 让 funcCtx 为使用 F 的 [[FormalParameters]] 内部值为函数代码建立新执行上下文的结果 属性,传递的参数 List args,以及 this 值 在 10.4.3 中描述。
  2. 令 result 为 FunctionBody 的计算结果,它是 F 的 [[Code]] 内部属性的值。如果 F 没有 [[Code]] 内部属性,或者如果它的值为空的 FunctionBody, 那么结果是(正常、未定义、空)。
  3. 退出执行上下文funcCtx,恢复之前的执行上下文。
  4. 如果 result.type 是 throw 则 throw result.value。
  5. 如果result.type是返回则返回result.value。
  6. 否则result.type必须正常。返回未定义。

【讨论】:

  • 嗨詹姆斯,我确实从那里开始,但是该功能会覆盖控制台的输出而不是添加到它,尽管您的答案是正确的,但它实际上不会输出到控制台
  • @Fibrewire - 您希望返回什么?原生的console.log方法返回undefined,所以没看出问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
相关资源
最近更新 更多