【发布时间】: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*/})()