在JavaScript函数中定义全局变量
可以在JavaScript函数中定义全局变量吗 我想在其他函数中使用在JavaScript函数中定义全局变量,javascript,function,variables,scope,declaration,Javascript,Function,Variables,Scope,Declaration,可以在JavaScript函数中定义全局变量吗 我想在其他函数中使用trailimage变量(在makeObj函数中声明) <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="
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 offsetfrommouse=[10,-20];
var displayduration=0;
选择的var obj_=0;
函数makeObj(地址){
**var trailimage=[地址,50,50]**
文件。写(“”);
所选对象=1;
}
函数truebody(){
返回(!window.opera&&document.compatMode&&document.compatMode!=“BackCompat”)?document.documentElement:document.body;
}
函数hidetrail(){
var x=document.getElementById(“trailimageid”).style;
x、 可见性=“隐藏”;
document.onmousemove=“”;
}
功能跟随鼠标(e){
var xcoord=offsetfrommouse[0];
var ycoord=offsetfrommouse[1];
var x=document.getElementById(“trailimageid”).style;
如果(类型e!=“未定义”){
xcoord+=e.pageX;
ycoord+=e.pageY;
}
else if(typeof window.event!=“未定义”){
xcoord+=truebody().scrollLeft+event.clientX;
ycoord+=truebody().scrollTop+event.clientY;
}
var-docwidth=1395;
var=676;
如果(xcoord+trailimage[1]+3>docwidth | | ycoord+trailimage[2]>docheight){
x、 display=“无”;
警惕(“inja”);
}
其他的
x、 显示=”;
x、 左=xcoord+“px”;
x、 top=ycoord+“px”;
}
如果(所选对象=1){
警报(“obj_selected=true”);
document.onmousemove=跟随鼠标;
如果(显示持续时间>0)
setTimeout(“hidetrail()”,显示持续时间*1000);
}
只需在函数外部声明它,并在函数内部赋值即可。比如:
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage = null ; // Global variable
function makeObj(address) {
trailimage = [address, 50, 50]; // Assign value
我希望这个例子能解释更多:
申报
var trialImage;
外面。然后
function makeObj(address) {
trialImage = [address, 50, 50];
...
...
}
不,你不能。只需在函数外部声明变量。您不必在赋值的同时声明它:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
正如其他人所说,您可以在全局范围内(在所有函数和模块之外)使用
var
来声明全局变量:
<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>
在浏览器上,您可以对名为窗口的全局窗口执行相同的操作:
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
模块中的顶级代码位于模块作用域,而不是全局作用域,因此创建了一个变量,该模块中的所有代码都可以看到,但该变量不是全局的
在没有模块支持的过时环境中,将代码包装在作用域函数中,并使用该作用域函数的局部变量,并在其中关闭其他函数:
<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>
(function(){//开始作用域函数
var yourGlobalVariable;//代码的全局性,在作用域函数之外不可见
函数foo(){
// ...
}
})(); // 端点作用域函数
它非常简单。在函数外部定义trailimage
变量,并在makeObj函数中设置其值。现在,您可以从任何地方访问它的值
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
...
}
如果要创建启动函数,可以通过以下方式定义全局函数和变量:
function(globalScope)
{
// Define something
globalScope.something()
{
alert("It works");
};
}(window)
因为函数是用这个参数全局调用的,所以这里是全局范围。因此,something应该是一个全局性的东西。如果你阅读了评论,就会对这个特定的命名约定进行很好的讨论
似乎自从我的答案发布后,命名惯例变得更加正式了。教授、写书等的人谈论var
declaration和function
declaration
以下是支持我观点的另一篇维基百科帖子:
…并回答主要问题。在函数之前声明变量。这将起作用,并且符合在作用域顶部声明变量的良好实践:)经典示例:
window.foo = 'bar';
一个现代、安全的例子,通过使用
如今,还可以选择使用:
或
就性能而言,我不确定它是否明显比在变量中存储值慢
广泛的浏览器支持,如上所述
我意识到这里面可能有很多语法错误,但这只是一般的想法。。。非常感谢LayZee指出这一点。。。您可以找到本地和会话存储的位置。我的代码也需要同样的东西,这是一个非常好的主意。以下是可能有用的示例代码
var Human = function() {
name = "Shohanur Rahaman"; // Global variable
this.name = "Tuly"; // Constructor variable
var age = 21;
};
var shohan = new Human();
document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable
var Human=function(){
name=“Shohanur-Rahaman”;//全局变量
this.name=“Tuly”//构造函数变量
年龄=21岁;
};
var shohan=新人类();
文件。写(shohan.name+“
”);
文件。填写(姓名);
文件。写(年龄);//未定义,因为它是局部变量
在这里我找到了一个很好的答案:这里有另一个简单的方法,可以使变量在其他函数中可用,而不必使用全局变量:
函数makeObj(){
//var trailimage=‘测试’;
makeObj.trailimage='test';
}
函数someOtherFunction(){
文件编写(makeObj.trailimage);
}
makeObj();
someOtherFunction()代码>如果希望函数内部的变量在函数外部可用,请返回函数内部变量的结果
var x=function returnX{var x=0;return x;}
就是这个想法
<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;
return trailimage;
}
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 offsetfrommous
function(globalScope)
{
// Define something
globalScope.something()
{
alert("It works");
};
}(window)
window.foo = 'bar';
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
localStorage.foo = 42;
sessionStorage.bar = 21;
var Global = 'Global';
function LocalToGlobalVariable() {
// This creates a local variable.
var Local = '5';
// Doing this makes the variable available for one session
// (a page refresh - it's the session not local)
sessionStorage.LocalToGlobalVar = Local;
// It can be named anything as long as the sessionStorage
// references the local variable.
// Otherwise it won't work.
// This refreshes the page to make the variable take
// effect instead of the last variable set.
location.reload(false);
};
// This calls the variable outside of the function for whatever use you want.
sessionStorage.LocalToGlobalVar;
var Human = function() {
name = "Shohanur Rahaman"; // Global variable
this.name = "Tuly"; // Constructor variable
var age = 21;
};
var shohan = new Human();
document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable
<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;
return trailimage;
}
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>
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
function firstFunction() {
if (typeof(testVar) === "undefined") {testVar = 1;} //initializing variable if not initialized
testVar += 1;
console.log('Test variable inside 1st function: '+testVar);
}
function secondFunction() {
testVar += 1;
console.log('Test variable inside 2nd function: '+testVar);
}
firstFunction();
secondFunction();
testVar += 1;
console.log('Test variable outside: '+testVar);