Chris Muench
Chris Muench

Reputation: 18318

IE 8 variable scope error

In IE 8, the second version of this causes the following error:

Object doesn't support this property or method.

The error is at map = new L.Map. In the first version, there are no errors.

I thought if you don't include var it automatically goes to global scope. Why would an error occur in IE 8? Note, this doesn't happen in IE 9.

var map;
jQuery(document).ready(function() 
{
    map = new L.Map('map', {'scrollWheelZoom': false});
 ...
}

VS:

jQuery(document).ready(function() 
{
    map = new L.Map('map', {'scrollWheelZoom': false});
 ...
}

Upvotes: 2

Views: 1142

Answers (2)

RobG
RobG

Reputation: 147363

In non–strict mode, assigning to an undeclared variable creates a global variable with the assigned value. Trying to access the value of an undeclared and uninitialised variable will throw a reference error:

x = 5;
alert( x ); // shows 5

alert( y ); // Error: y is undefined
y = 10;

Declared variables are processed before any code is executed so they don't throw reference errors.

However, you aren't getting a reference error, you're getting one that IE throws when an attempt is made to call a non–existent method of an object, so likely there is an attempt to access window.map() or similar:

e.g. in IE:

var o = {};
o.x(); // Object doesn't support this property or method

Whether this is the answer to your issue is unknown, does new L.Map(...) return an object that can be called?

Upvotes: 0

Esailija
Esailija

Reputation: 140210

I thought if you don't include var it automatically goes to global scope.

This is incredibly bad practice because there is no way to tell whether you intended that. It also causes an error in strict mode.

It also causes bugs in IE when you have some element with the name map on the document.

You can explicitly create a global like this:

jQuery(document).ready(function() {
    window.map = new L.Map('map', {
        'scrollWheelZoom': false
    });
});

Here you make your intent clear and won't get this error.


Here are the jsfiddles to demonstrate it (Run in IE8 or lower):

http://jsfiddle.net/3Jn5N/ works

http://jsfiddle.net/3Jn5N/1/ doesn't work

Upvotes: 6

Related Questions