如何从另一个 JS 文件调用 Javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6712087/
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
How to call Javascript function from another JS file
提问by Briz
Yes, I have both functions included in html. I know the ordering matters. What I'm confused about is the way that the JS functions are set up, and I don't know the right way to call the function I want.
是的,我在 html 中包含了这两个功能。我知道订购很重要。我困惑的是JS函数的设置方式,我不知道调用我想要的函数的正确方法。
For example, I have a Items.js
, in which I show some things on the screen, but I want to hide all of those items when the user activates something in a Phone.js
例如,我有一个Items.js
,其中我在屏幕上显示了一些东西,但是当用户在一个Phone.js
How Items.js
is set up:
如何Items.js
设置:
Items = function()
{
this.stop = function()
{
// Items are hidden
$(this.ButtonDiv).hide();
$(this.CounterDiv).hide();
}
}
Now how do I call the stop function from Phone.js
?
现在我如何调用 stop 函数Phone.js
?
回答by Ram
Rather that declaring Items as a function try this:
而不是将 Items 声明为函数试试这个:
var Items = {
stop: function() {
// Items are hidden
$(this.ButtonDiv).hide();
$(this.CounterDiv).hide();
}
}
And call the function like: Items.stop();
并调用函数,如: Items.stop();
回答by Michael Berkowski
Items.js
must be loaded first. Inside Phone.js
you can call the function as:
Items.js
必须先加载。在内部,Phone.js
您可以将函数调用为:
Items.stop();
If that doesn't work (though I think it should), create a class instance of Items()
first and then call the stop()
method:
如果这不起作用(尽管我认为应该这样做),Items()
请先创建一个类实例,然后调用该stop()
方法:
var items = new Items();
items.stop();
回答by Joe
Just make sure that Items.js is loading before Phone.js
只要确保 Items.js 在 Phone.js 之前加载
<script src="Items.js"></script>
<script src="Phone.js"></script>
回答by qwertymk
You can change it like so:
你可以像这样改变它:
var Items = new (function()
{
this.stop = function()
{
// Items are hidden
$(this.ButtonDiv).hide();
$(this.CounterDiv).hide();
}
})();
And call it like so:
并像这样称呼它:
Items.stop();