0

I have an array of functions like this:

var myFuncs = {
firstFun: function(string) {
// do something},
secondFunc: function(string) {
// do something},
thirdFunc: function(string) {
// do something
}}

What I want is, for example, to put the first two functions, firstFun{} and secondFunc{}, into separate js file, firstsecondFun.js using jQuery function or other approaches talked in How do I include a JavaScript file in another JavaScript file?

var myFuncs = {
jQuery.getScript("firstsecondFun.js", function(){
alert("Script loaded and executed.");
// // Here you can use anything you defined in the loaded script
}),
thirdFunc: function(string) {
// do something
}};p

firstsecondFun.js will be like:

firstFun: function(string) {
// do something},
secondFunc: function(string) {
// do something}

either with or without var myFuncs = {} so in the end the var myFuncs = {} will just the same as all functions in it.

I tried myFuncs.push but it does not work.

Community
  • 1
  • 1

3 Answers3

0

Once you have created the object myfuncs you can simply add new properties using object notation.

var myFuncs = {
   firstFun: function(string) { /* do something*/}
}

in another file loaded after first file

myFuncs.secondFunc = function(string) {  /* do something else*/}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

It's not array. but you can use class in javascript to do it :) ...

function myFuncs(){
      this.firstFun = function(string){
      /* do something*/
      }
      this.secondFunc = function(string){
      /* do something*/
      }
      this.thirdFunc = function(string){
      /* do something*/
      }
}

how to use it:

var curFuncs= new myFuncs();
curFuncs.firstFun(/* string value */);
or curFuncs.secondFunc(/* string value */);
or curFuncs.thirdFunc(/* string value */);
HoangHieu
  • 2,802
  • 3
  • 28
  • 44
0

Provided content of firstseconfFun.js would be:

var firstSecond = {
  firstFun: function(string) {},
  secondFunc: function(string) {}
}

Then, in your main file, put this code.

var myFuncs = {
  thirdFunc: function(string) {
    // do something
  }
}

jQuery.getScript("firstsecondFun.js", function(){
  for(var k in firstSecond) {
    myFuncs[k] = firstSecond[k]
  }
});

I haven't tested, but this should work.

Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • Thanks for the solution. Would the code in the last paragraph overwrite the "thirdFunc" since myFuncs[0] = thirdFunc? – user2773103 Jul 11 '14 at 23:16
  • No. it won't overwrite. And `myFuncs[0]` is not `thirdFunc`. `myFuncs` is not an array but an object. `myFuncs['thirdFunc']` is the function you need. – Jashwant Jul 12 '14 at 04:28