Javascript: Correct way to declare functions dynamically

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');

Problem courtesy of: Sean Bannister

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Javascript: Correct way to declare functions dynamically

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录