简体   繁体   中英

Javascript Prototype method and un-used variables

I am currently building objects via prototype method. This object requires no user built methods and while a factory approach may be better here, I am more comfortable with prototyping.

I am wondering about the var buf = data._raw; . What happens to buf once the object is returned, does it create a memory leak or is it garbage collected or does something else happen?

var Identification = function(data){
  var buf = data._raw;

  this.def = data.def;
  this.master = buf.readUInt8(9);
  this.version = buf.readUInt8(10);
  //more reading from a buffer...
}

module.exports = Identification;

I call this function in another module by passing in data which consists of 3 properties. def , _raw , length where def is an int representation of the object type, _raw is a buffer, and length is the buffer length.

var Identification = require('./Identification');

function main(){
  var identification = new Identification(data);
}

main();

Is this bad practice? Am I opening up my code for issues in the future?

Thanks.

What happens to buf once the object is returned?

It is garbage collected, as nothing does reference the variable/value any more. Your constructor doesn't seem to export closures that would still be able to access buf .

does it create a memory leak?

No, why would it? Standard garbage collection rules apply for constructor functions as well.

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