简体   繁体   English

在另一个js文件中使用javascript函数

[英]using a javascript function inside another js file

i'm following along a book and I have 2 javascript files. 我正在跟着一本书,我有2个javascript文件。 Both are in the HTML file as: 两者都在HTML文件中:

<script src="playlist_store.js"></script>
<script src="playlist.js"></script>

however, when I try to call a function from playlist_store.js inside of playlist.js chrome debugger says "uncaught reference error. loadPlaylist is not defined. loadPlaylist() is the function from playlist_store.js 但是,当我尝试从playlist.js中的playlist_store.js调用一个函数时,chrome调试器会说“未捕获的引用错误。”loadPlaylist未定义.loadPlaylist()是来自playlist_store.js的函数

I thought there might be a typo somewhere but I don't think there is. 我以为某处可能有拼写错误,但我认为不存在。 Does playlist.js actually need to somehow import or include / require the playlist_store.js ? playlist.js实际上是否需要以某种方式导入或包含/需要playlist_store.js? Is the browser not smart enough to somehow link them so the functions in one you can call from another? 浏览器是否不够智能以某种方式链接它们,以便您可以从另一个中调用其中的功能?

Defining a function like follows 定义如下函数

function myaction () { }

is a named (private) function. 是一个命名 (私有)函数。
It is better to write a (private) function assigned to a variable: 编写分配给变量的(私有)函数会更好:

var myaction = function () { };

Now what you need is a function, that is assigned to a variable in the global object: 现在你需要的是一个函数,它被赋值给全局对象中的变量:

myaction = function () { };
// or strict:
window.myaction = function () { };

It is now a global (public) function, so you can use it outside of your defining .js. 它现在是一个全局(公共)函数,因此您可以在定义的.js之外使用它。

Beware that the first example, a function statement doesn't have a semicolon. 请注意第一个示例,函数语句没有分号。 Using the function operator as in the other examples, you need a semicolon. 像在其他示例中一样使用函数运算符,您需要一个分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM