在JavaScript函数中定义全局变量 [英] Define global variable in a JavaScript function

查看:124
本文介绍了在JavaScript函数中定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在JavaScript函数中定义一个全局变量?



我想使用 trailimage 变量(在> makeObj 函数中声明)。

html xmlns =http://www.w3.org/1999/xhtml>
< head id =Head1runat =server>
< title>< / title>
< script type =text / javascript>
var offsetfrommouse = [10,-20];
var displayduration = 0;
var obj_selected = 0;
函数makeObj(address){
** var trailimage = [address,50,50]; **
document.write('< img id =trailimageidsrc =' + trailimage [0] +'border =0style =position:absolute; visibility:visible; left:0px; top:0px; width:'+ trailimage [1] +'px; height:'+ trailimage [ 2] +'px>');
obj_selected = 1;


函数truebody(){
return(!window.opera&& document.compatMode&&&& document.compatMode!=BackCompat)? document.documentElement:document.body;
}
函数hidetrail(){
var x = document.getElementById(trailimageid)。style;
x.visibility =hidden;
document.onmousemove =;
}
函数followmouse(e){
var xcoord = offsetfrommouse [0];
var ycoord = offsetfrommouse [1];
var x = document.getElementById(trailimageid)。style;
if(typeof e!=undefined){
xcoord + = e.pageX;
ycoord + = e.pageY;
}
else if(typeof window.event!=undefined){
xcoord + = truebody()。scrollLeft + event.clientX;
ycoord + = truebody()。scrollTop + event.clientY;
}
var docwidth = 1395;
var docheight = 676;
if(xcoord + trailimage [1] + 3> docwidth || ycoord + trailimage [2]> docheight){
x.display =none;
alert(inja);
}
else
x.display =;
x.left = xcoord +px;
x.top = ycoord +px;


if(obj_selected = 1){
alert(obj_selected = true);
document.onmousemove = followmouse;
if(displayduration> 0)
setTimeout(hidetrail(),displayduration * 1000);
}
< / script>
< / head>
< body>
< form id =form1runat =server>
top:219px; position:绝对;高度:138px;宽度:120pxonclick =javascript:makeObj('Pictures / sides / sides-not-clicked.gif'); />
< / form>
< / body>
< / html>


解决方案

是的,正如其他人所说的,您可以使用 var 在全局范围(所有函数之外)声明一个全局变量:

 <脚本> 
var yourGlobalVariable;
函数foo(){
// ...
}
< / script>

或者,您可以指定<窗口:

 < script> 
函数foo(){
window.yourGlobalVariable = ...;
}
< / script>

...因为在浏览器中,所有全局变量 var 窗口对象的属性。 (在最新的ECMAScript 2015规范中,新的 let const class 语句在全局作用域创建全局对象的属性; ES2015中的新概念。) =http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html>隐含全局的恐怖,但不要故意这样做,尽力去做避免这样做,也许是通过使用ES5的use strict。)



所有这些都说: d如果可能的话,避免使用全局变量(几乎可以肯定)。正如我所提到的,它们最终是 window 的属性,而 window 已经是足够拥挤 所有具有 id 的元素(以及很多只有名称)被转储(不管即将到来的规范如何,IE转储几乎所有的名称



相反,将您的代码封装在一个范围函数中,并使用该范围函数的局部变量,并使其中的其他函数关闭:

 < script> 
(function(){//开始范围函数
var yourGlobalVariable; //全局代码,在范围函数外部不可见
函数foo(){
// .. 。
}
})(); //结束范围函数
< / script>


Is it possible to define a global variable in a JavaScript function?

I want use the trailimage variable (declared in the makeObj function) in other functions.

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
        <script type="text/javascript">
            var offsetfrommouse = [10, -20];
            var displayduration = 0;
            var obj_selected = 0;
            function makeObj(address) {
                **var trailimage = [address, 50, 50];**
                document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0"  style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
                obj_selected = 1;
            }

            function truebody() {
                return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
            }
            function hidetrail() {
                var x = document.getElementById("trailimageid").style;
                x.visibility = "hidden";
                document.onmousemove = "";
            }
            function followmouse(e) {
                var xcoord = offsetfrommouse[0];
                var ycoord = offsetfrommouse[1];
                var x = document.getElementById("trailimageid").style;
                if (typeof e != "undefined") {
                    xcoord += e.pageX;
                    ycoord += e.pageY;
                }
                else if (typeof window.event != "undefined") {
                    xcoord += truebody().scrollLeft + event.clientX;
                    ycoord += truebody().scrollTop + event.clientY;
                }
                var docwidth = 1395;
                var docheight = 676;
                if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
                    x.display = "none";
                    alert("inja");
                }
                else
                    x.display = "";
                x.left = xcoord + "px";
                x.top = ycoord + "px";
            }

            if (obj_selected = 1) {
                alert("obj_selected = true");
                document.onmousemove = followmouse;
                if (displayduration > 0)
                    setTimeout("hidetrail()", displayduration * 1000);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px;
            top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
        </form>
    </body>
</html>

解决方案

Yes, as the others have said, you can use var at global scope (outside of all functions) to declare a global variable:

<script>
var yourGlobalVariable;
function foo() {
    // ...
}
</script>

Alternately, you can assign to a property on window:

<script>
function foo() {
    window.yourGlobalVariable = ...;
}
</script>

...because in browsers, all global variables global variables declared with var are properties of the window object. (In the latest specification, ECMAScript 2015, the new let, const, and class statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)

(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)

All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
    var yourGlobalVariable; // Global to your code, invisible outside the scoping function
    function foo() {
        // ...
    }
})();         // End scoping function
</script>

这篇关于在JavaScript函数中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆