我们可以在另一个 JS 文件中调用用一个 JavaScript 编写的函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3809862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:14:15  来源:igfitidea点击:

Can we call the function written in one JavaScript in another JS file?

javascriptinclude

提问by Hemant Kumar

Can we call the function written in one JS file in another JS file? Can anyone help me how to call the function from another JS file?

我们可以在另一个JS文件中调用一个JS文件中编写的函数吗?谁能帮助我如何从另一个 JS 文件调用该函数?

回答by Edgar Hernandez

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

只要在第一次使用函数之前加载了包含函数定义的文件,就可以像在同一个 JS 文件中一样调用该函数。

I.e.

IE

File1.js

文件1.js

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

File2.js

文件2.js

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

HTML

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>

The other way won't work.As correctly pointed out by Stuart Wakefield. The other way will also work.

另一种方法行不通。正如Stuart Wakefield正确指出的那样。另一种方式也将起作用。

HTML

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>

What will not work would be:

不起作用的是:

HTML

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>

Although alertOneis defined when calling it, internally it uses a function that is still not defined (alertNumber).

尽管alertOne在调用时已定义,但在内部它使用了一个尚未定义的函数 ( alertNumber)。

回答by Stuart Wakefield

The answer above has an incorrect assumption that the order of inclusion of the files matter. As the alertNumber function is not called until the alertOne function is called. As long as both files are included by time alertOne is called the order of the files does not matter:

上面的答案有一个错误的假设,即文件的包含顺序很重要。因为在调用alertOne 函数之前不会调用alertNumber 函数。只要两个文件都包含在alertOne被调用的时间里,文件的顺序无关紧要:

[HTML]

[HTML]

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

[JS]

[JS]

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

Or it can be ordered like the following:

或者可以按如下方式订购:

[HTML]

[HTML]

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

[JS]

[JS]

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

But if you were to do this:

但如果你要这样做:

[HTML]

[HTML]

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

[JS]

[JS]

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

It only matters about the variables and functions being available at the time of execution. When a function is defined it does not execute or resolve any of the variables declared within until that function is then subsequently called.

只与执行时可用的变量和函数有关。定义函数时,它不会执行或解析其中声明的任何变量,直到随后调用该函数。

Inclusion of different script files is no different from the script being in that order within the same file, with the exception of deferred scripts:

包含不同的脚本文件与脚本在同一文件中的顺序没有区别,但延迟脚本除外:

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

then you need to be careful.

那么你需要小心。

回答by jball

As long as both are referenced by the web page, yes.

只要网页引用了两者,就可以。

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

您只需调用函数,就好像它们在同一个 JS 文件中一样。

回答by Pramendra Gupta

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.jswill be available to other js files - say b.jsas long as both a.jsand b.jsare included in the file using the following include mechanism(and in the sameorder if the function in b.js calls the one in a.js).

您在一个 .js 文件中编写的 js 函数和变量 - 比如说a.js将可用于其他 js 文件 - 比如说b.js只要a.jsb.js都包含在使用以下包含的文件中机制(如果 b.js 中的函数调用 a.js 中的函数,则以相同的顺序)。

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

回答by Kamil Kie?czewski

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

ES6:不是<script>在 .html中包含许多 js 文件,您可以只包含一个主文件,例如script.js使用属性type="module"support),并且在内部script.js您可以包含其他文件:

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

And in script.jsfile include another file like that:

script.js文件中包含另一个这样的文件:

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

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

在“module.js”中,您必须导出您将导入的函数/类

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

Working example here.

工作示例在这里

回答by anishMarokey

yes you can . you need to refer both JS fileto the .aspxpage

是的你可以 。你需要两指JS file.aspx页面

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

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

JScript1.js

JScript1.js

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

回答by Digvijay

Well, I came across another sweet solution.

window['functioName'](params);

好吧,我遇到了另一个甜蜜的解决方案。

window['functioName'](params);

回答by ronatory

For those who want to do this in Node.js(running scripts on the server-side) another option is to use requireand module.exports. Here is a short example on how to create a module and export it for use elsewhere:

对于那些想要在Node.js(在服务器端运行脚本)中执行此操作的人,另一个选择是使用requiremodule.exports。这是一个关于如何创建模块并将其导出以在其他地方使用的简短示例:

file1.js

文件1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

文件2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};

回答by sheetal

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-

您可以从您正在使用的文件中调用在另一个 js 文件中创建的函数。因此,首先您需要将外部 js 文件添加到 html 文档中作为-

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

The function defined in the external javascript file -

外部 javascript 文件中定义的函数 -

$.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');

回答by Consta Gorgan

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

这是一个更具描述性的示例,附有 CodePen 片段:

1.js

1.js

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

2.js

2.js

function clickedTheButton() {
  fn1();
} 

index.html

索引.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

Output. Button + Result

Try this CodePen snippet: link.

试试这个 CodePen 片段:链接