最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How can I access a variable from another file in Javascript? - Stack Overflow

programmeradmin4浏览0评论

Let's say that I have two files that are in separate directories:

/folder1/first.js

/folder1/folder2/second.js

first.js contains a variable called newName. Would it be possible to access it in second.js? (and how)?

EDIT: The HTML file is located in the same directory as first.js.

Let's say that I have two files that are in separate directories:

/folder1/first.js

/folder1/folder2/second.js

first.js contains a variable called newName. Would it be possible to access it in second.js? (and how)?

EDIT: The HTML file is located in the same directory as first.js.

Share Improve this question edited Jun 2, 2019 at 13:25 wh1te_d1ce asked Jun 2, 2019 at 2:30 wh1te_d1cewh1te_d1ce 831 gold badge1 silver badge9 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 6

You should use export function in the first.js file and use require in second.js to access that variable.

For example If you have var named first in first .js.

const first = {
name: 'dharmik',
age: '21'
}

Export it like this:

export { first };

And then import in second.js like this:

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

And then you can use the variable in second.js.

console.log(first.name); //dharmik

Assuming you are just linking static HTML files with <script> tags, then they will share their global scope. In other words: yes, second.js will be able to access the top-level variables from first.js, assuming they were liked in that order. Directories have no bearing on the behavior.

You'd use import/export syntax.

In first.js:

let newName = "New Name";
export { newName };

In second.js:

import { newName } from "./../first.js";

Technically yes this is possible, if you are going to access it from "second.js"

<script src="../first.js">
//code here that uses the global variable from first.js
</script>

The .. allows for file directory traversal, by going up 1 directory.

发布评论

评论列表(0)

  1. 暂无评论