简体   繁体   中英

Sharing JS functions between files without making them global or attaching them to a global object?

Say that I've got a function that I want to re-use between multiple files. I could just make it global but that's no good.

master_file.js

add = function(num1, num2){
  return num1 + num2;
};

subtract = function(num1, num2){
  return num1 - num2
};

file1.js

add(4,4);

file2.js

add(9,1);

file3.js

subtract(8,2);

Instead, I can create a global object and attach the functions as values of the global object (or the window object as others do).

master_file_v2.js

var add = function(num1, num2){
  return num1 + num2;
};

var subtract = function(num1, num2){
  return num1 - num2
};

global = {

  add: function(num1, num2){
    return add(num1, num2);
  },
  subtract: function(num1, num2){
    return subtract(num1, num2);
  }

};

Then I would have to call the functions like so.

file1.js

global.add(4,4);

file2.js

global.add(9,1);

file3.js

global.subtract(8,2);

Is there a way to not call the functions like this? I would prefer to directly call them by their names just like before, but without declaring them as global.

file1.js

add(4,4);

file2.js

add(9,1);

file3.js

subtract(8,2);

If you want to avoid using globals (you should!), you should take a look at CommonJS or Harmony modules.

Using a module system would allow you to do things like this:

//utils.js

module.exports = function () {
  return {
    add: function (num1, num2) {
      return add(num1, num2);
    },
    subtract: function (num1, num2) {
      return subtract(num1, num2);
    }
  };
};

//file1.js

var add = require('./utils').add;
var subtract = require('./utils').subtract;

add(4,4);
subtract(8,2);

or event better using Harmony's destructuring feature:

var {add, subtract} = require('./utils');

add(4,4);
subtract(8,2);

Using modules makes your code more modular and makes code reuse easy while keeping your global scope clean.

It is possible by using with , but that was deprecated. The preferred method is to assign them to a local variable, basically the inverse of what you did in master_file

file1.js

var add = global.add
add(4,4);

file2.js

var add = global.add
add(9,1);

file3.js

var subtract = global.subtract
subtract(8,2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM