이것은 자바스크립트 함수를 정의할 수 있는 글로벌 변수?
'내가 원하는 트레이리마거' 변수 (선언된 wt. '마이크로비' 기능) 을 사용하여 다른 총괄하였습니다.
<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 선언을 전역 변수.
<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>
또는 '윈도' 속성을 지정할 수 있습니다.
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
,,, 모든 브라우저에서 리베카우스 < s> 글로벌 variables< /s>. 전역 변수 var '이' 윈도 '을 (를)' 의 속성을 객체에는 선언했다. (이번 사양명세, ecmascript (,) 은 2015년 새 'let', '상수' 및 '클래스' 글로벌 만들 수 있는 t # 39 의 속성을 명령문입니다 dell. 글로벌 유효범위 aren& 글로벌 객체에는;; 새 콘셉트로 ES2015.)
(There& # 39, s 도 현장을 암시적입니다 글로벌 하지만 don& # 39, t do it 고의적으로요 및 최선을 다해 피하기 위해 그렇게 우연히 아마도 ES5& 사용하여, s ',' # 39 를 사용하여 strict" ".)
모든 것을 밝혔다. # 39 i& 피할 수 있는 전역 변수를 가능한 경우, d (진실이며당신이 거의 확실히 (수). 앞서 언급했듯이, 그들은 이미 '창' 및 '창' 의 속성을 끝날 수도 있다는 우려가 제기되고 있다. 많은 만큼 충분한 어떤 있는 요소를 모두 갖춘 'id' (및 다수의 부트해 a '이름') 기술입니까 덤프했습니다 항목이없습니다 (및 관계 없이 그 어떤 것에 관하여 '이름' 를 통해 향후 사양명세, 그냥 IE 덤프합니다 좁히어).
로컬 영역 범위 설정 기능 및 변수를 사용할 수 있는 랩 대신 당신의 코드에서 사용 중인 다른 함수 안에서 함수를 저회가 폐쇄에.
<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>
UPDATE1: 좋은 의견 읽을 경우 there& 대한 논의, s # 39 이 특정 명명 규칙.
UPDATE2: 이 때문에 그동안 공식 홈페이지에 글을 올려 명명 규칙 제 대답은 된 것으로 보인다. 사람은 책을 쓰기 등을 가르치는 ',' var 대해 이야기하고 선언, '기능을' 선언.
UPDATE3: 다음은 추가 위키백과 게시물로의 敲阀汽俊 汲摹窍妨绰 내 포인트: http://en.wikipedia.org/wiki/Declaration_ (computer_programming) # Declarations_and_Definitions
.and 응답하는 주요 질문. 변수 선언 전에 확인 기능. 이렇게 하면 작동합니까 또 준수하십시오 변수를 선언할 수 있는 좋은 것이 맨 위에 유효범위:)
그냥 너희가운데 내부에서 외부로 기능 및 할당 값을 총괄하였습니다. 다음과 같은 항목을
<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". 제공하는 기능도 있지만, 이 때문에 전역 변수 이름 안에 대해 한 번 밖에 너희가운데 것이 깔끔한 코드. 또한 작업:
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
trailimage = [address, 50, 50]; //GLOBAL VARIABLE , ASSIGN VALUE
이 예는 더 좋겠다 "고 설명했다.
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);
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 - Its 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;
아마 이건 내가 많은 구문 오류 등 일반 아이디어를 얻을 수 있다. 너무 감사하고 레이제이 위해 이 문제를 지적했다. 로컬 및 세션 스토리지 (http://www.w3schools.com/html/html5_webstorage.asp.) 는 어떻게 찾을 수 있습니다. 나는 내 코드와 같은 이는 정말 필요한 게 좋을 듯하다.
클래식 (예:
window.foo = 'bar';
예를 들어, best practice 를 사용하여 다음과 같은 현대 안전하다구요 인생:
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
요즘은 # 39, s 도 there& 사용하는 옵션을 웹스터거 apiu
localStorage.foo = 42;
또는
sessionStorage.bar = 21;
사용할 수 있습니까?. 에서 설명한 것처럼 넓게퍼진 브라우저 지원
외부에서 사용할 수 있도록 변수 함수 내에 다운로드하려는 함수은? 왜안돼요 반품하십시오 변수 함수 내에 결과를? 'var x = {var 레터너스 함수은 x = 0; 반품하십시오 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 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 cause its local variable
여기서 I found a nice 오토메이티드 전역 변수를 선언할 수 있는 방법은 하나 javascript 에서
여기 다른 방법을 사용하지 않고도 쉽게 하기 위해 다른 기능을 사용할 수 있는 변수를 전역 변수.
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
function makeObj() {
// var trailimage = 'test';
makeObj.trailimage = 'test';
}
function someOtherFunction() {
document.write(makeObj.trailimage);
}
makeObj();
someOtherFunction();
끝 - < 스니핏 >;!
시작프로그램을 함수은 할 경우 이런 식으로 글로벌 함수와 변수를 정의할 수 있습니다.
function(globalScope)
{
//define something
globalScope.something() {
alert("It works");
};
}(window)
이 때문에 이 인수를 통해 글로벌 유효범위 목마르겠구나 호출되었을 전역으로라는 기능이 있다. 따라서 노드전역 뭔가 해야 할 일이다.