【问题标题】:How can [this] be undefined in strict mode?[this] 如何在严格模式下未定义?
【发布时间】:2016-06-01 13:26:22
【问题描述】:

当我在 Chrome 中运行此代码时,我得到一个 Uncaught TypeError: Cannot read property 'concat' of undefined

function _log()
{
    'use strict'

    [this].concat(Array.from(arguments)).forEach(
        function (obj) { console.log(obj) }
    )
}

_log('foo', 'bar');

我不明白为什么会这样。 [this] 怎么可能是未定义的?即使this 未定义,[this] 也应该是一个数组,不是吗?

一个有趣的细节是,当我从函数中删除 use strict 行时,错误消失并且代码按预期运行,将函数上下文和参数分别记录在新行上。

在我不知道的严格模式下使用关键字this 可能有什么特别之处吗?

谢谢。

【问题讨论】:

    标签: javascript this strict-mode


    【解决方案1】:

    这是一个有趣的错误:

    你只是忘记了'use strict'后面的分号,这完全改变了代码的解析方式:

    'use strict'[this].concat...
    

    您正在获取“use strict”链中名为 "[Object window]" 的属性。当然是undefined,所以它没有任何名为"concat"的属性。

    【讨论】:

    • 你以前不是有别的名字吗?! o_O
    • @Liam 你在想“dystroy”吗?那是前一阵子
    • @Lynn 你让我挠了几分钟,在那里。而且我想我不是唯一一个。
    • 啊,是的,就是这样。 #着名inyourownlifetime :)
    猜你喜欢
    • 2017-01-07
    • 2018-03-24
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2019-06-29
    • 2015-01-04
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多