简体   繁体   English

为什么console.log停止javascript库中的错误?

[英]Why does console.log stop errors in javascript Library?

I have been toying with creating a small library for a web app I am working on. 我一直在为正在开发的Web应用程序创建一个小型库。 In creating this library, I can enter a log statement at the top of the script, and everything below works fine. 在创建此库时,我可以在脚本顶部输入一个log语句,下面的所有内容都可以正常工作。 However, if I remove the top console.log statement, I get errors. 但是,如果删除顶部的console.log语句,则会出现错误。 Code is below. 代码如下。 Errors are: 错误是:

ReferenceError: assignment to undeclared variable TestFirst

Code: 码:

$(document).ready(function() {
    (function() {
        console.log('starting');
        'use strict';
        function define_TestFirst()  {
            function TestFirst () {};
            return TestFirst;
        }

        if (typeof(TestFirst) === 'undefined') {
            console.log('defined');
            TestFirst = define_TestFirst();
            TestFirst.prototype.test = function () {
                console.log('TestFirst object created.');
            }
        } else {
            console.log('TestFirst library already defined!');
        }
    })();
});

The problem is that the "use strict" must be the first statement of your function in order to be used. 问题在于, "use strict"必须是您的函数的第一条语句才能被使用。 It's ignored otherwise. 否则将被忽略。

Now, I guess that you see the problem: 现在,我想您已经看到了问题:
The problem is not about removing the top console.log , it's about use strict being no longer ignored. 问题不在于删除顶级console.log ,而是关于不再use strict忽略use strict

The problem with your script running in strict mode is that any variable must be declared first : 您的脚本在严格模式下运行的问题在于必须首先声明任何变量:

ReferenceError: assignment to undeclared variable TestFirst

Means that you need to add the var statement at var TestFirst = define_TestFirst(); 意味着您需要在var TestFirst = define_TestFirst();处添加var语句TestFirst = define_TestFirst();

As the error says, you did not declare TestFirst with var but assign a value to it (or use window.TestFirst = ... ): 如错误所示,您没有使用var 声明 TestFirst ,而是为其分配了一个值(或使用window.TestFirst = ... ):

TestFirst = define_TestFirst();

You want strict mode, but having the console.log() before the use strict causes the use strict to not enable strict mode. 您需要严格模式,但是在use strict之前use strict console.log()会导致use strict不启用严格模式。

From MDN: 从MDN:

To invoke strict mode for an entire script, put the exact statement "use strict"; 要为整个脚本调用严格模式,请输入确切的语句“ use strict”; (or 'use strict';) before any other statements. (或“使用严格”;)之前的任何其他声明。

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

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