0

I want to permit to call digest method only once, so function is deleted when digest has been calculated and that is a simple object without functions.

var Content = function(filename) {
  var that = {};
  var name = path.basename(filename);

  var digest = function(callback) {
    fs.readFile(filename, function(err, data) {
      that.hash = crypto.createHash('sha1').update(data).digest('hex');
      delete that.digest; // IS THIS SAFE?
      callback();
    });
  };

  that.digest = digest;
  that.name = name;

  return that;
};

Use it:

var content = Content('/path/to/file');
content.digest(function() {
  // content.hash is available
});

Is this safe and good practice?

1
  • possible is better use simple flag? Commented Nov 28, 2013 at 11:03

1 Answer 1

2

Yes it's safe because delete just removes that reference, it doesn't free any memory so your function is still there:

Unlike what common beliefs suggests, the delete operator has nothing to do with directly freeing memory (it only does indirectly via breaking references.

Is it a good practice? Well this is just my opinion...I think it's not really clear when you read that code (you need to read it all to understand what happens) so I would avoid it in favor of something else (if you're using some kind of lazy initialization you may use another property, for example). That said with proper comments in code...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.