是否可以在JavaScript函数中定义全局变量?
我想在其他函数中使用trailimage变量(在makeObj函数中声明)。
trailimage
makeObj
<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>
是的,正如其他人所说的,您可以var在全局范围内(在所有函数之外)使用声明全局变量:
var
<script> var yourGlobalVariable; function foo() { // ... } </script>
或者,您可以在上分配一个属性window:
window
<script> function foo() { window.yourGlobalVariable = ...; } </script>
…因为在浏览器中,用声明的 所有全局变量var都是window对象的属性。(在最新规范ECMAScript 2015中,全局范围内的new let,const和class语句创建的不是全局对象属性的全局变量;这是ES2015中的新概念。)
let
const
class
(也有隐式全局变量的恐怖,但不要故意这样做,并尽最大努力避免偶然地这样做,也许可以使用ES5 "use strict"。)
"use strict"
话虽如此:如果可能(我几乎可以肯定),我会避免使用全局变量。正如我所提到的,它们最终是的属性window,并且window已经非常 拥挤 了所有元素id(其中很多(仅包含一个name))被转储到其中(无论即将发布的规范是什么,IE都将其中name存在的任何内容都转储了))。
id
name
而是将代码包装在作用域函数中,并使用该作用域局部变量,并在其中封闭其他函数:
<script> (function() { // Begin scoping function var yourGlobalVariable; // Global to your code, invisible outside the scoping function function foo() { // ... } })(); // End scoping function </script>