2

I'm having trouble getting my head around declaring functions dynamically. I tried to ask this question so it was more generic but I really don't know what I'm doing in this case and kept coming back to my code.

I have a json object which contains log levels (as seen in code below) and for each log level I need to create a function so I can call, for example: log.info('my log message');

The problem I'm experiencing is when I call log.info() I can't figure out that 'info' was called for all I know log.error() could of been called because all these functions contain the same dynamic code and I don't know a way to detect what function called this.

I hope that makes sense. I'm writing this for Node.js so my code so far is below. I have a comment saying where my problem function is and where I want the log level to display.

exports.logger = function() {

  // Syslog severity levels
  var levels = {
    emerg: { "code": 0 },
    alert: { "code": 1 },
    crit: { "code": 2 },
    error: { "code": 3 },
    warning: { "code": 4 },
    notice: { "code": 5 },
    info: { "code": 6 },
    debug: { "code": 7 }
  };

  // Loop through each severity level
  for (var severity in levels) {
    // Ensure we're not iterating over a prototype
    if (levels.hasOwnProperty(severity)) {
      // Declare function
      this[severity] = function(message) {
        // Here's the problem: I have no idea what called this function.
        console.log('Log severity level here:', message);
      };    
    }
  }
}

This is how I call it:

var logger = require('log.js');
var log = new (logger.logger)(
  // settings removed for example
);
log.info('test');

2 Answers 2

4
Object.keys(levels).forEach(function (severity) {
  this[severity] = function (message) {
    console.log(severity, message);
  });
}, this);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for saving my sanity, was stuck on this for hours :)
1

This is very similar to this recent question: Creating closures within a for loop - am I doing this right?. People, don't create closures in a loop!

  for (var severity in levels) {
    if (levels.hasOwnProperty(severity)) {
      this[severity] = createLogger(severity);
    }
  }

  function createLogger(severity) {
      return function(message) {
        console.log(severity, message);
      }
   }

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.