简体   繁体   中英

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.

The result of require function is cached, so it would be the same only within a single process .

By the way, I cannot understand why you require a.js twice. Why not just do

//d.js
var a = require("./a.js");
function () {
    a();
    var b = require("./b.js");
    assert(b.test === 555); // success!
}
function () { // no dupes!
    a();
}

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