ham*_*mze 479 javascript variables scope declaration function
是否可以在JavaScript函数中定义全局变量?
我想在其他函数中使用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>
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 711
是的,正如其他人所说,您可以var在全局范围内(在所有函数之外)使用来声明一个全局变量:
<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>
Run Code Online (Sandbox Code Playgroud)
或者,您可以在以下位置分配属性window:
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
Run Code Online (Sandbox Code Playgroud)
...因为在浏览器中,声明的所有全局变量全局变量var都是window对象的属性.(在最新的规范中,ECMAScript 2015,全局范围内的new let,const和class语句创建的全局变量不是全局对象的属性;这是ES2015中的一个新概念.)
(还有隐式全局变量的恐怖,但不要故意这样做,尽量避免意外地使用它,也许是使用ES5 "use strict".)
所有这一切:如果你可能的话,我会避免全局变量(你几乎可以肯定).正如我所提到的,它们最终成为了属性window,并且window已经足够拥挤了所有元素与id(并且很多只有一个name)被抛弃在其中(并且无论即将到来的规范,IE转储几乎任何东西都name在那里).
相反,将代码包装在作用域函数中并使用该作用域函数的本地变量,并使其中的其他函数闭包:
<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>
Run Code Online (Sandbox Code Playgroud)
op1*_*kun 19
更新1:如果您阅读了这些评论,那么就这个特定的命名约定进行了很好的讨论.
UPDATE2:似乎自从我的回答发布后,命名约定变得更加正式.教书,写书等的人谈论var宣言和function宣言.
UPDATE3:这是支持我的观点的附加维基百科帖子:http://en.wikipedia.org/wiki/Declaration_ ( computer_programming)#Declarations_and_Definitions
......并回答主要问题.函数前的DECLARE变量.这将起作用,它将符合在范围顶部声明变量的良好实践:)
har*_*ihb 14
只是声明
var trialImage;
Run Code Online (Sandbox Code Playgroud)
外.然后
function makeObj(address) {
trialImage = [address, 50, 50];
..
..
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
Dhr*_*hak 11
只需在函数外部声明它,并在函数内部赋值.就像是:
<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
Run Code Online (Sandbox Code Playgroud)
或者简单地从函数内部的变量名中删除"var"也会使其成为全局变量,但最好将其声明为一次以获得更清晰的代码.这也有效:
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
trailimage = [address, 50, 50]; //GLOBAL VARIABLE , ASSIGN VALUE
Run Code Online (Sandbox Code Playgroud)
我希望这个例子能够解释更多:http://jsfiddle.net/qCrGE/
var globalOne = 3;
testOne();
function testOne()
{
globalOne += 2;
alert("globalOne is : " + globalOne );
globalOne += 1;
}
alert("outside globalOne is : " + globalOne);
testTwo();
function testTwo()
{
globalTwo = 20;
alert("globalTwo is " + globalTwo);
globalTwo += 5;
}
alert("outside globalTwo is :" + globalTwo);
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 11
不,你不能.只需在函数外声明变量即可.您不必在分配值的同时声明它:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
Run Code Online (Sandbox Code Playgroud)
小智 11
JavaScript 中的作用域分为三种类型:
如果在变量名之前添加Var,则其作用域由其所在位置决定
例子:
var num1 = 18; // Global scope
function fun() {
var num2 = 20; // Local (Function) Scope
if (true) {
var num3 = 22; // Block Scope (within an if-statement)
}
}
Run Code Online (Sandbox Code Playgroud)
num1 = 18; // Global scope
function fun() {
num2 = 20; // Global Scope
if (true) {
num3 = 22; // Global Scope
}
}
Run Code Online (Sandbox Code Playgroud)
经典例子:
window.foo = 'bar';
Run Code Online (Sandbox Code Playgroud)
使用IIFE遵循最佳实践的现代、安全示例:
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
Run Code Online (Sandbox Code Playgroud)
如今,还可以选择使用WebStorage API:
localStorage.foo = 42;
Run Code Online (Sandbox Code Playgroud)
或者
sessionStorage.bar = 21;
Run Code Online (Sandbox Code Playgroud)
就性能而言,我不确定它是否比在变量中存储值明显慢。
这很简单。trailimage在函数外部定义变量并在makeObj函数中设置其值。现在您可以从任何地方访问它的价值。
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
...
}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
我意识到这可能有很多语法错误,但它的总体思路...非常感谢 LayZee 指出这一点...您可以在http://www.w3schools找到本地和会话存储。 com/html/html5_webstorage.asp。我的代码需要同样的东西,这是一个非常好的主意。
//编辑
截至(我相信)2015 年,引入了 javascript(如果您愿意)的新“标准”。该标准为 javascript 引入了许多新想法,其中之一就是范围的实现。
https://www.w3schools.com/js/js_scope.asp有关于这个想法的所有细节,但悬崖指出:
const 定义一个常数。
var 具有“全局”范围。
let 具有“功能”或“块”范围。
是的你可以。只是不要使用 var,不要使用 let。只需初始化变量,它就会自动分配为全局变量:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
971731 次 |
| 最近记录: |