Pergunta

If the variable foo is undefined, normally I can do things like:

!foo;
foo === undefined;
foo !== 'some value';

However, the code base that I am working on now has something in it that seems to instruct the browser's interpreter to throw an exception for any operation on an undefined variable other than this:

typeof foo !="undefined";

I'm working in the same browsers that I normally work in (Chrome and Firefox). But I'm coming on to this project in the middle this time instead of starting from scratch. It is a dJango project using Backbone.js, underscore, handlebars, jQuery, yepnope.

Could this behavior be due to the instruction "use strict" appearing somewhere in the global namespace? I did a search in the project for the text string "use strict" and found it in some code that seems to come from twitter:

    Files: bootstrap.js
           script.js
    From:  http://twitter.github.com/bootstrap/javascript.html#transitions

I also found it in the json2 file. However I'm pretty sure this file didn't cause me problems last time I worked with it:

    File: json2.js
    From: http://www.JSON.org/json2.js

For all I know, this isn't even caused by the inclusion of "use strict" somewhere...

Any ideas?

Thanks so much!

Foi útil?

Solução

There's an important difference between undefined and undeclared.

function test() {
    var foo;
    if (foo) { /* not executed */ }
}

This is fine because foo is declared, but its value is undefined.

function test() {
    if (foo) { /* exception! */ }
}

This will throw an exception (ReferenceError) because foo is not declared. (Unless there is a window.foo.)

Outras dicas

When a variable is undeclared, you cannot use it in comparisons.

undeclaredvar = 1;

is the only thing that works: undeclaredvar is implicitly declared in the global namespace.

Strict mode declarations inside a function will never "leak" the strictness to the global scope. So, "use strict"; in Twitter bootstrap / JSON2 won't affect the strictness of your script.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top