[英]Calling a method within an object from a different file?
Hello guys decide to refactor my javascript and try to seperate my onpage script to external js file. 大家好,我决定重构我的JavaScript,并尝试将我的页面脚本分离到外部js文件中。
please correct me if I am wrong, am still new to javascript, but this is the current setup I have:- my external file :- 如果我错了,请更正我,它仍然不是javascript的新手,但这是当前的设置,我具有:-我的外部文件:-
exJS = function(){
this.coolMethod = function(){
//do cool code here
}
}
onpage Script:- 页面脚本:
<script type="text/javascript" src="ex_js.js"></script>
<script>
exJs = new exJS();
exJs.coolMethod();
</script>
So obviously I am doing something wrong, How can I call a method within an object from a different file ? 所以很明显我在做错事,如何从另一个文件中调用对象中的方法?
I also welcome better suggestions to carry this out 我也欢迎更好的建议来执行此操作
Thank you 谢谢
update: It didn't work as I didn't place a comma between the functions I have defined within an object ... silly mistake !! 更新:它没有用,因为我没有在对象中定义的函数之间放置逗号...愚蠢的错误!
What you do is fine (apart the badly closed first script element), but probably not needed if you don't want more than one instance of exJS. 您所做的一切都很好(除了紧密关闭的第一个脚本元素之外),但如果您不希望有多个exJS实例,则可能不需要。
I'd suggest this little variant : 我建议这个小变化:
External file : 外部档案:
var exJS = {
coolMethod: function(){
//do cool code here
}
}
onpage Script: 页面脚本:
<script type="text/javascript" src="ex_js.js"></script>
<script>
exJs.coolMethod();
</script>
Note that when your code grows and you want to define a new function in another file, you may simply define this function as 请注意,当代码增长时,您想在另一个文件中定义一个新函数,则可以简单地将该函数定义为
exJS.doSomeOtherThing = function() {
...
}
I would look at using namespaces (or at least javascripts attempt at them) 我会考虑使用名称空间(或者至少是javascript尝试使用它们)
Here is an example, the accepted answer shows how to do it. 这是一个示例,已接受的答案显示了如何执行此操作。
How do I declare a namespace in JavaScript? 如何在JavaScript中声明名称空间?
@dystroy also has an example of this in his answer. @dystroy在回答中也有一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.