Global javascript variable inside document.ready

前端 未结 8 1877
感情败类
感情败类 2020-12-08 04:04

Which is the right way of declaring a global javascript variable? The way I\'m trying it, doesn\'t work

$(document).ready(function() {

    var intro;

    i         


        
相关标签:
8条回答
  • 2020-12-08 05:03

    If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...

    var MyProject = {};
    $(document).ready(function() {
        MyProject.intro = "";
    
        MyProject.intro = "something";
    });
    
    console.log(MyProject.intro); // "something"
    
    0 讨论(0)
  • 2020-12-08 05:03

    JavaScript has Function-Level variable scope which means you will have to declare your variable outside $(document).ready() function.

    Or alternatively to make your variable to have global scope, simply dont use var keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.

    $(document).ready(function() {
       intro = null; // it is in global scope now
    

    To learn more about it, check out:

    • Explaining JavaScript Scope And Closures
    0 讨论(0)
提交回复
热议问题