lundi 20 avril 2015

understanding require() with module.exports with javascript and browserify

I am a c++ programmer at heart and I'm currently being thrown into the deep end with javascript and asked to swim very quick. I am using browserify so I am able to use the require function that node.js uses to get get access to code in other files. Now everything I have done seems to be working fine, I am just unsure that I am doing it correctly.

//a.js
module.exports = function(){
    alert("hello world");
}

//b.js
var myClass = new MyClass();
module.exports = myClass;

//c.js
var a = require("./a.js");
a();
var b = require(./b.js");
b.prototype.test = 555;

//d.js
function () {
    var a = require("./a.js");
    a();
    var b = require(./b.js");
    assert(b.test === 555);
}
function () { // duplicated require called inside same file but different function
    var a = require("./a.js");
    a();
}

So in every function and every file I want to use a.js do I have to put the require call? Seems like it will get a bit convoluted. Is there a better way to do this? Also assuming that c.js is ran before d.js will the assert pass or does it result in a copy being created of myClass so the objects are different between C and D?

Thanks for any help.

Aucun commentaire:

Enregistrer un commentaire