1

Here, I have this two code :

var mod = function() {
   var a = function() {
      this.fucname = 'hello';
    };

    a.prototype.build = function() {
      return 'before '+this.fucname;
    };

    return new a();
 };

for( var i=0; i<10000; i++ ){
  var newfuc = mod();
};

and

var a = function() {
  this.fucname = 'hello';
};

a.prototype.build = function() {
  return 'before '+this.fucname;
};

for( var i=0; i<10000; i++ ){
   var newfuc = new a();
};

After I check both in chrome dev, the second code take a JS HEAP 3.0MB, the first code take a JS HEAP 10MB.

Is that mean, the build function has been created 10000 time in the first code? and how can I refine it without remove the cover mod?

I have to pass something into the function...

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Both the `build` and the `a` functions, yes. Is calling a “module” 10,000 times a realistic situation you’re going to have to deal with? (Note also that it’s not a memory leak, just some excess consumption.) – Ry- Mar 07 '17 at 03:59
  • yes, and also i have to pass some variable inside, without remove the cover "mod" – user3769916 Mar 07 '17 at 04:02
  • So change your code so that having a `mod` function was justified. – zerkms Mar 07 '17 at 04:11
  • Read about the revealing prototype pattern. – Bergi Mar 07 '17 at 04:38
  • I have edited the title of your question as I had no idea what you meant with "relationship" (answering the literal question: none). I'm still unsure how closures are relevant to you question at all. – Bergi Mar 07 '17 at 04:41
  • @Bergi thank for that! – user3769916 Mar 07 '17 at 04:54

1 Answers1

2

If you want to hide the constructor but also only evaluate it once, you can make use of an IIFE to create a new scope:

var mod = (function() {
  var a = function() {
    this.fucname = 'hello';
  };

  a.prototype.build = function() {
    return 'before ' + this.fucname;
  };

  return function() {
    return new a();
  };
})();

for (var i = 0; i < 10000; i++) {
  var newfuc = mod();
}
Ry-
  • 218,210
  • 55
  • 464
  • 476