Reputation: 487
Hello guys decide to refactor my javascript and try to seperate my onpage script to external js file.
please correct me if I am wrong, am still new to javascript, but this is the current setup I have:- my external file :-
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 !!
Upvotes: 1
Views: 4909
Reputation: 382514
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.
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() {
...
}
Upvotes: 1
Reputation: 7905
I would look at using namespaces (or at least javascripts attempt at them)
Here is an example, the accepted answer shows how to do it.
How do I declare a namespace in JavaScript?
@dystroy also has an example of this in his answer.
Upvotes: 0