Programming

하나의 JavaScript로 작성된 함수를 다른 JS 파일로 호출 할 수 있습니까?

procodes 2020. 5. 15. 21:11
반응형

하나의 JavaScript로 작성된 함수를 다른 JS 파일로 호출 할 수 있습니까?


한 JS 파일로 작성된 함수를 다른 JS 파일로 호출 할 수 있습니까? 다른 JS 파일에서 함수를 호출하는 방법을 알려주는 사람이 있습니까?


함수 정의를 포함하는 파일이 함수를 처음 사용하기 전에로드 된 경우 동일한 JS 파일에있는 것처럼 함수를 호출 할 수 있습니다.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

다른 방법으로는 작동하지 않습니다. 스튜어트 웨이크 필드가 올바르게 지적했듯이 . 다른 방법으로도 효과가 있습니다.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

작동하지 않는 것은 다음과 같습니다.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

alertOne호출 할 때 정의 되지만 내부적으로 여전히 정의되지 않은 함수를 사용합니다 ( alertNumber).


위의 답변에는 파일 포함 순서가 중요하다는 잘못된 가정이 있습니다. alertNumber 함수는 alertOne 함수가 호출 될 때까지 호출되지 않습니다. 두 파일이 시간별로 포함되어있는 한 alertOne은 파일의 순서는 중요하지 않습니다.

[HTML]

<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript">
    alertOne( );
</script>

[JS]

// File1.js
function alertNumber( n ) {
    alert( n );
};
// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// Inline
alertOne( ); // No errors

또는 다음과 같이 주문할 수 있습니다.

[HTML]

<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript">
    alertOne( );
</script>

[JS]

// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// File1.js
function alertNumber( n ) {
    alert( n );
};
// Inline
alertOne( ); // No errors

그러나 당신이 이것을해야한다면 :

[HTML]

<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript">
    alertOne( );
</script>
<script type="text/javascript" src="file1.js"></script>

[JS]

// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// Inline
alertOne( ); // Error: alertNumber is not defined
// File1.js
function alertNumber( n ) {
    alert( n );
};

실행 시점에 사용 가능한 변수와 함수에 대해서만 중요합니다. 함수가 정의되면 해당 함수가 호출 될 때까지 선언 된 변수를 실행하거나 해결하지 않습니다.

다른 스크립트 파일의 포함은 지연된 스크립트를 제외하고 동일한 파일 내에서 순서대로있는 스크립트와 다르지 않습니다.

<script type="text/javascript" src="myscript.js" defer="defer"></script>

조심해야합니다.


웹 페이지에서 둘 다 참조하는 한 가능합니다.

You simply call the functions as if they are in the same JS file.


If all files are included , you can call properties from one file to another (like function, variable, object etc.)

The js functions and variables that you write in one .js file - say a.js will be available to other js files - say b.js as long as both a.js and b.js are included in the file using the following include mechanism(and in the same order if the function in b.js calls the one in a.js).

<script language="javascript" src="a.js"> and 
<script language="javascript" src="b.js">

yes you can . you need to refer both JS file to the .aspx page

<script language="javascript" type="text/javascript" src="JScript1.js">
 </script>

    <script language="javascript" type="text/javascript" src="JScript2.js">
    </script>

JScript1.js

function ani1() {
    alert("1");
    ani2();
}
JScript2.js
function ani2() {
    alert("2");
}

ES6: Instead of including many js files using <script> in .html you can include only one main file e.g. script.js using attribute type="module" (support) and inside script.js you can include other files:

<script type="module" src="script.js"></script>

And in script.js file include another file like that:

import { hello } from './module.js';
...
// alert(hello());

In 'module.js' you must export function/class that you will import

export function hello() {
    return "Hello World";
}

Working example here.


You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

참고URL : https://stackoverflow.com/questions/3809862/can-we-call-the-function-written-in-one-javascript-in-another-js-file

반응형