javascript – 控制台返回undefined

前端之家收集整理的这篇文章主要介绍了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.@H_502_36@
  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).@H_502_36@
  3. Exit the execution context funcCtx,restoring the prevIoUs execution context.@H_502_36@
  4. If result.type is throw then throw result.value.@H_502_36@
  5. If result.type is return then return result.value.@H_502_36@
  6. Otherwise result.type must be normal. Return undefined.@H_502_36@

猜你在找的JavaScript相关文章