IT story

다른 파일에서 변수에 액세스 할 수 있습니까?

hot-time 2020. 6. 15. 08:10
반응형

다른 파일에서 변수에 액세스 할 수 있습니까?


first.js다른 파일 안에 있는 파일에 변수를 사용할 수 second.js있습니까?

first.js라는 변수를 포함합니다 colorcodes.


Fermin이 말했듯이 전역 범위의 변수는 선언 된 후로드 된 모든 스크립트에 액세스 할 수 있어야합니다. window또는 전역 범위에서 속성을 사용 this하여 동일한 효과를 얻을 수도 있습니다.

// first.js
var colorCodes = {

  back  : "#fff",
  front : "#888",
  side  : "#369"

};

... 다른 파일에서 ...

// second.js
alert (colorCodes.back); // alerts `#fff`

... html 파일에서 ...

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

다음을 사용하여 첫 번째 파일에서 변수를 내보낼 수 있습니다 수출 .

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

그런 다음 import를 사용하여 변수를 두 번째 파일로 가져옵니다 .

//second.js
import { colorCode } from './first.js'

수출-MDN


이것은 작동해야합니다-firstfile에서 전역 변수를 정의하고 secondfile에서 액세스하십시오.

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js :

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js :

do_something_with(colors.background);

스크립트 파일을로드하는 순서는 일부 브라우저에서 중요합니다 (IE6, 아마도 다른 브라우저).


위의 답변 이 마음에 들었지만 나와 함께 작동하지 않았습니다.

내가이 declaring변수 insideJQuery 이기 때문에$( document ).ready()

<script>다른 곳이 아닌 태그 안에 변수를 선언하십시오.


amplify.js발견했습니다 . 사용하기 정말 간단합니다. 값을 저장하려면 "myValue"라고하겠습니다.

amplify.store("myKey", "myValue")

액세스하려면

amplify.store("myKey")

전역 변수에 색상 코드를 저장하면 자바 스크립트 파일에서 색상 코드에 액세스 할 수 있어야합니다.


나는 이것을 조금 다르게하고있을 수 있습니다. 이 구문을 왜 사용했는지 잘 모르겠으며 오래 전에 책에서 복사했습니다. 그러나 각각의 js 파일은 변수를 정의합니다. 아무 이유없이 첫 번째 파일을 R이라고합니다.

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

그런 다음 분리하려는 큰 코드 조각이 있으면 별도의 파일과 다른 변수 이름에 넣지 만 R 변수와 함수를 계속 참조 할 수 있습니다. 나는 아무 이유없이 새로운 하나의 TD를 불렀습니다.

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

TD 'sepfunction'에서 R.somefunction을 호출하는 것을 볼 수 있습니다. 두 스크립트를 모두로드해야하기 때문에 이것이 런타임 효율성을 제공하지는 않지만 코드 구성을 유지하는 데 도움이됩니다.


Node.js를 사용하면 모듈을 통해 변수를 내보낼 수 있습니다.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

그런 다음 require를 사용하여 모듈 / 변수를 두 번째 파일로 가져옵니다.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.


One best way is by using window.INITIAL_STATE

<script src="/firstfile.js">
    // first.js
    window.__INITIAL_STATE__ = {
      back  : "#fff",
      front : "#888",
      side  : "#369"
    };
</script>
<script src="/secondfile.js">
    //second.js
    console.log(window.__INITIAL_STATE__)
    alert (window.__INITIAL_STATE__);
</script>

참고URL : https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file

반응형