简体   繁体   English

Javascript使用严格的错误没有捕获

[英]Javascript use strict error not catching

I am creating a backbone.js app that uses require.js for AMD. 我正在创建一个使用require.js for AMD的backbone.js应用程序。 In order to check for use strict support in the browser, I have included the following code. 为了在浏览器中检查use strict支持,我已经包含以下代码。 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. 但是,当代码运行时, var o = {p:1, P:2}抛出的错误不会像我预期的那样被捕获,而是会杀死整个页面。

Chrome console prints this error: Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode Chrome控制台会输出以下错误: Uncaught SyntaxError:严格模式下不允许在对象文字中复制数据属性

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. 这样,您可以独立测试并根据结果运行不同的代码分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM