【问题标题】:Uncaught SyntaxError: Unexpected eval or arguments in strict mode: window.gtag = (arguments) => dataLayer.push(arguments);Uncaught SyntaxError: Unexpected eval or arguments in strict mode: window.gtag = (arguments) => dataLayer.push(arguments);
【发布时间】:2018-07-09 05:22:56
【问题描述】:

我有以下代码:

class MetricGoogleGateway extends AMetricGateway{
    constructor(id, name, token) {
        super(id, name);
        this.token = token;
    }

    configure() {
        if(!window.dataLayer && !window.gtag)
        {
             window.dataLayer = window.dataLayer || [];
             window.gtag = (arguments) => dataLayer.push(arguments);
        }

        gtag('js', new Date());
        gtag('config', 'UA-113071675-1');
    }
}

当浏览器加载文件时,出现以下错误:

Uncaught SyntaxError: Unexpected eval or arguments in strict mode

但如果我在 chrome 控制台中运行以下行,一切正常:

window.dataLayer = window.dataLayer || [];
window.gtag = (arguments) => dataLayer.push(arguments);
window.gtag(1);
window.gtag(2);
console.log(window.dataLayer)
-> console.log result: [1,2]

注意:

我注意到如果我换行了:

window.gtag = (arguments) => dataLayer.push(arguments);

对于线路:

window.gtag = function(arguments) { dataLayer.push(arguments) }

我遇到同样的错误

【问题讨论】:

  • 改用window.gtag = (arg) => dataLayer.push(arg);。 “严格”模式特别关注在函数中使用 arguments 标识符。 arguments 以外的任何标识符都应解决此 SyntaxError
  • 因为控制台不是严格模式。如果您像这样在控制台中运行代码,它将无法工作:(function(){"use strict"; /*put your code here*/})()

标签: javascript ecmascript-6


【解决方案1】:

您的代码位于 class 主体内,该主体在 strict mode 中运行(就像您的所有代码一样),与粘贴到控制台中的 sn-p 不同。

名称argumentseval 是特殊的,禁止用作标识符。不要使用它们。只需写 args 代替,或者更好的是像 layer 这样真正有意义的东西。

window.gtag = (layer) => dataLayer.push(layer);

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 2019-02-19
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多