HeWhoProtects
HeWhoProtects

Reputation: 487

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.

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

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

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

Jon Taylor
Jon Taylor

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

Related Questions