【发布时间】:2022-12-12 08:01:43
【问题描述】:
如何在 javascript 文件“test.js”中定义方法“foo”,以便我可以将该文件导入另一个 javascript 文件并调用方法“foo”?
【问题讨论】:
标签: javascript
如何在 javascript 文件“test.js”中定义方法“foo”,以便我可以将该文件导入另一个 javascript 文件并调用方法“foo”?
【问题讨论】:
标签: javascript
要在 JavaScript 文件 test.js 中定义可以从另一个 JavaScript 文件导入和调用的方法 foo,您可以使用以下语法:
// test.js
export function foo() {
// method code goes here
}
这在 test.js 中定义了一个名为 foo 的函数,并使其可用于导入到另一个文件中。要从另一个 JavaScript 文件导入并调用 foo 方法,可以使用以下代码:
import { foo } from './test.js';
foo();
这从 test.js 导入 foo 函数并调用它,执行函数内的代码。
选择:
import * as test from './test.js';
test.foo();
【讨论】:
要在名为 test.js 的 JavaScript 文件中定义一个名为 foo 的方法,您可以使用以下代码:
// Define the foo function
function foo() {
// Do something here
}
// Export the foo function so that it can be imported by other files
module.exports = {
foo: foo,
};
要将 foo 函数导入另一个 JavaScript 文件,可以使用以下代码:
// Import the foo function from the test.js file
const { foo } = require('./test.js');
// Call the foo function
foo();
或者,您可以使用导入语法导入 foo 函数,如下所示:
// Import the foo function from the test.js file using the import syntax
import { foo } from './test.js';
// Call the foo function
foo();
请注意,导入语法仅在现代浏览器中受支持,并且需要在旧浏览器中使用转译器,例如 Babel。另一方面,所有现代和旧版浏览器都支持 require 语法。
【讨论】: