I have been toying with creating a small library for a web app I am working on. In creating this library, I can enter a log statement at the top of the script, and everything below works fine. However, if I remove the top console.log statement, I get errors. 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. 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.
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();
As the error says, you did not declare TestFirst
with var
but assign a value to it (or use 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.
To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.