Javascript使用严格的错误没有捕获 [英] Javascript use strict error not catching
问题描述
我正在创建一个使用require.js for AMD的backbone.js应用程序。为了在浏览器中检查使用严格
支持,我已经包含以下代码。但是,当代码运行时, var o = {p:1,P:2}
引发的错误不会像我预期的那样被捕获,而是会被杀死整个页面。
I am creating a backbone.js app that uses require.js for AMD. In order to check for use strict
support in the browser, I have included the following code. However, when the code is run, the error thrown by var o = {p:1, P:2}
is not caught as I expect it to be, and instead kills the entire page.
Chrome控制台打印此错误: 未捕获的SyntaxError:严格模式下不允许在对象文字中复制数据属性
Chrome console prints this error: Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode
require([
'jquery',
'underscore',
'backbone',
'src/app'
], function(jQuery, _, Backbone, App){
"use strict"
var tooOld = true,
isStrictMode = function () {
try{
var o = {p:1, p:2};
} catch (e) {
tooOld = false;
new App;
} finally {
if (tooOld) {
// Display some message
}
}
}();
});
为什么错误导致我的页面崩溃而不是被抓住?我该如何解决这个问题?
Why is the error crash my page instead of being caught? How can I fix this?
推荐答案
如果您想检查严格模式支持,请考虑:
If you want to check for strict mode support, consider:
function supportsStrict() {
'use strict';
return typeof function(){return this;}() == 'undefined';
}
console.log(supportsStrict()); // true if supports strict mode
这样您可以独立测试并运行不同的代码分支,具体取决于结果。
That way you can test independently and run different code branches depending on the result.
这篇关于Javascript使用严格的错误没有捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!