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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...