微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 控制台返回undefined

参见英文答案 > Why does this JavaScript code print “undefined” on the console?1个
所以我劫持了控制台功能
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发布了以下代码作为问题的答案.对答案的评论已移至对该问题的评论.

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

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

解决方法

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

例如:

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

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

  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.

原文地址:https://www.jb51.cc/js/150438.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐