2017-05-15 2 views
0

다음 스크립트 블록의 인스턴스를 각각 고유 한 변수 값 (변수 이름은 같음)을 갖고이 블록 다음에 오는 외부 j가 실행될 때 액세스 할 수 있습니까? 동일한 변수 선언되면/두 번째로 할당되도록여러 인라인 자바 스크립트 블록에서 변수 읽기

<script type="text/javascript"> 
 
/*<![CDATA[*/ 
 
my_key = "1a"; 
 
my_time = new Date().getTime(); 
 
my_custom_params = {}; 
 
/*]]>*/ 
 
</script> 
 
<script type='text/javascript' src='run.js?id=1901'></script>

+1

FYI''type = "text/javascript"'는'script '엘리먼트와'/ * * /'는'script' 태그를 XML 구문 분석기에 전달하지 않는 한 제거 될 수 있습니다 (거의 없습니다). –

+0

https://jsfiddle.net/bus2z1oj/ – guest271314

+0

블록에 여러 개의 외부 js 파일이 있습니까? – Bergi

답변

1

그것은 모든 변수가 동일한 전역 범위에 있기 때문에 복잡하지만, 각 선언 스크립트가 직접 스크립트 뒤에 때 값을 사용, 그것은 참으로 가능 :

<script type="text/javascript"> 
my_key = "1a"; 
my_time = new Date().getTime(); 
my_custom_params = {}; 
</script> 
<script type="text/javascript"> 
(function(key, time, params) { 
    // scoped variables only available in here 
    // won't be overwritten by the following script 
}(my_key, my_time, my_custom_params)); 
</script> 
<script type="text/javascript"> 
// overwrites the variables 
my_key = "2b"; 
my_time = new Date().getTime(); 
my_custom_params = {}; 
</script> 
<script type="text/javascript"> 
{ 
    const locals = { 
     key: my_key, 
     time: my_time, 
     params: my_custom_params 
    }; 
    // locals.… available only in this scope 
    // the object won't be overwritten or mutated by following scripts 
} 
</script> 
… 

당신은 다음 번에 덮어 쓰기하기 전에 전역 변수를 평가하고, 어떤 안전한 장소에 그 값을 저장해야합니다.

물론, 여전히 끔찍한 습관입니다. 각 스크립트가 고유 한 네임 스페이스 (객체)를 만들고 그 값을 거기에 넣어야합니다.

+0

좋아요! 브라우저에서 표준 및 일관성이 있습니까? – ramiwi

+0

예, 모든 표준 브라우저에서 작동합니다. (OK, 새로운 것에서 만'const' 블록 범위의 것) – Bergi

1

script 요소는 모두 기본적으로, 동일한 "범위"와 그 범위에 존재는, 그것을 "글로벌"인 이전 값을 덮어 씁니다.

우리는 "전역"범위를 피하기 위해이 기능을 사용하여 코드 모듈을 생성합니다.

변수가 선언되고 초기화 된 후 외부 스크립트가 실행되고 다른 스크립트의 범위에 액세스 할 수 있으면 외부 스크립트에서 변수에 액세스하는 것이 가능합니다.

전역 범위를 피하려면 함수 나 개체와 같이 작은 범위에서 변수를 사용할 수 있도록해야합니다. 스콧의 답변을 완료하려면

<script> 
 

 
    (function(){ 
 
    var my_key = "1a"; 
 
    var my_time = new Date().getTime(); 
 
    var my_custom_params = {}; 
 
    
 
    // Make a dummy object, give it new properties and assign the private values to them 
 
    var dummy = {}; 
 
    dummy.my_key = my_key; 
 
    dummy.my_time = my_time; 
 
    dummy.my_custom_params = my_custom_params; 
 
    
 
    // Expose the dummy object via a custom property on the global object 
 
    window.myCustomNamespace = dummy; 
 
    }()); 
 

 

 

 
</script> 
 

 
<script> 
 
    // As long as this code executes after the above code, it doesn't matter if this code 
 
    // is in an external file or not. 
 

 
    // We can now access the data via the custom namespace: 
 
    console.log(window.myCustomNamespace.my_key); 
 
    console.log(window.myCustomNamespace.my_time); 
 
    console.log(window.myCustomNamespace.my_custom_params); 
 

 
</script>

1

:

<script> 
 

 
    var my_key = "1a"; 
 
    var my_time = new Date().getTime(); 
 
    var my_custom_params = {}; 
 
    
 
    console.log(my_key); 
 
    console.log(my_time); 
 
    console.log(my_custom_params); 
 

 
</script> 
 

 
<script> 
 
    // These assignments will overwrite the earlier values: 
 
    my_key = "2b"; 
 
    my_time = new Date().getTime(); 
 
    my_custom_params = {other:"value"}; 
 
    
 
    console.log(my_key); 
 
    console.log(my_time); 
 
    console.log(my_custom_params); 
 

 
</script>

여기 전역을 피하지만, 다른 코드에 변수를 사용할 수 있도록하는 방법의 예 즉시 호출 된 함수 식 (IIFE)은 jus입니다. t 옵션 문제는 글로벌 범위에서 충돌을 피하기위한 고립 된 범위의 생성입니다. 따라서, ES6 덕분에, 당신은 또한이 작업을 수행 할 수 있습니다 :

<script> 
 
{ 
 
    let my_key = "1a"; 
 
    let my_time = new Date().getTime(); 
 
    let my_custom_params = {foo: 'Foo'}; 
 
    
 
    console.log(my_key, my_time, my_custom_params); 
 
} 
 
</script> 
 

 
<script> 
 
{ 
 
    let my_key = "1b"; 
 
    let my_time = new Date().getTime(); 
 
    let my_custom_params = {bar: 'Bar'}; 
 
    
 
    console.log(my_key, my_time, my_custom_params); 
 
} 
 
</script>