码迷,mamicode.com
首页 > Web开发 > 详细

js声明全局变量的方式

时间:2018-10-05 23:04:20      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:class   world   声明   全局   func   on()   相同   def   define   

在js中有3中声明全局变量的方式

第一种使用var+变量名,在方法外部声明:

 
 1 var msg; //默认值undefined
 2 $(function(){
 3     setmsg();
 4     showmsg();
 5 })
 6 function setmsg(){
 7     msg = "hello world";
 8 }
 9 function showmsg(){
10     alert(msg);
11 }
 

第二种方式在方法内部声明,但是不使用var关键字:

 
 1 $(function(){
 2    setmsg();
 3    showmsg();
 4 })
 5 function setmsg(){
 6    msg = "hello world";
 7 }
 8 function showmsg(){
 9    alert(msg);
10 }
 

第三种是使用window全局对象:

 
 1 $(function(){
 2    setmsg();
 3    showmsg();
 4 })
 5 function setmsg(){
 6     window.msg = "hello world";
 7 }
 8 function showmsg(){
 9     alert(window.msg);
10 }
 

三种方式的运行结果都是相同的

js声明全局变量的方式

标签:class   world   声明   全局   func   on()   相同   def   define   

原文地址:https://www.cnblogs.com/journey-mk5/p/9746201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!