ReferenceError: variable is not defined

前端 未结 3 1201
南旧
南旧 2020-11-30 05:51

I met this issue sometimes but still don\'t know what causes it.

I have this script in the page:

$(function(){
    var value = \"10\";
});

相关标签:
3条回答
  • 2020-11-30 06:10

    Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

    Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

    var value;
    $(function() {
      value = "10";
    });
    console.log(value); // 10
    

    Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

    It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

    var value;
    console.log(value);
    value = "10";
    

    See also:

    • What is the scope of variables in JavaScript?
    • I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?
    0 讨论(0)
  • 2020-11-30 06:22

    Got the error (in the function init) with the following code ;

    "use strict" ;
    
    var hdr ;
    
    function init(){ // called on load
        hdr = document.getElementById("hdr");
    }
    

    ... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

    The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

    The fix for this was to change

    var hdr ;
    

    to

    var hdr = null ;
    
    0 讨论(0)
  • 2020-11-30 06:35

    It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var:

    $(function(){
        value = "10";
    });
    value; // "10"
    

    This is equivalent to writing window.value = "10";.

    0 讨论(0)
提交回复
热议问题