控制台返回undefined [英] Console returns undefined

查看:151
本文介绍了控制台返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经劫持了控制台功能

so ive 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 cant figure out why which leads me to think there is something slightly wrong here

Hello world由 log.call生成(控制台,a)按预期

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

submitmsg()是我的自定义函数

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

this is working exactly how i want, as i said though im slightly concerned that it is also returning "undefined" for reasons i do not understand.

注意:以下代码由OP发布,作为问题的答案。有关答案的评论已转移至该问题的评论。

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 the correct code should be the following?

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


推荐答案

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

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.

例如:

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

这是在 [[Call]] 内部方法规范(以粗体显示的相关点):

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



  1. 让funcCtx成为使用F的[[FormalParameters]]内部
    属性的值为函数代码建立新执行上下文的结果,传递的参数列出了args,这个值在10.4.3中描述为

  2. 让结果成为评估FunctionBody的结果,即F的值[[Code] ]]内部财产。如果F没有
    [[Code]]内部属性或者它的值是一个空的FunctionBody,那么
    则结果是(正常,未定义,空)。

  3. 退出执行上下文funcCtx,恢复上一个执行上下文。

  4. 如果result.type是throw则抛出result.value。

  5. 如果result.type为return,则返回result.value。

  6. 否则result.type必须正常。返回undefined。

  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.


这篇关于控制台返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆