0

I'm learning JavaScript/Node and I found out a way to create functions from an array in ES5 but not in ES6.

ES5

const methods = ['info', 'warm', 'debug', 'error', 'fatal']
function Logger(name){
    this.name = name;
    return this
}

methods.forEach((method) => {
    Logger.prototype[method] = function (msg) {
        tags = {}
        tags.id = uuidv1()
        tags.level = method.toUpperCase()
        tags.event = msg
        tags.timestamp = Date.now()
        console.log(tags)
    }
})

So when I call

log.fatal('fatal error')

Prints the correct way I want to do little bit the same but in ES6 using Classes

So far I have ES6

class Logger {
    constructor(name) {
        this._name = name;
    }
    get name() {
        return this._name
    }
    set name(name) {
        this._name = name
    }
//I tried with iterator but it wasn't correct.
    * [methods]()
    methods.forEach(method =>{
        [method] = function (msg) {
            tags = {}
            tags.id = uuidv1()
            tags.level = method.toUpperCase()
            tags.event = msg
            tags.timestamp = Date.now()
            console.log(json2tags(tags))
        }
    })

}

Thank you!

Julian Mendez
  • 3,162
  • 2
  • 13
  • 36
  • You should be able to do the same loop over the `class` as you did before. `class` compiles to prototypes anyway...it is just syntax sugar. – wjvander Mar 13 '18 at 14:13

1 Answers1

0

ES6 classes are (mostly) syntax sugar for the JavaScript OOP model. You still can modify the prototype like you would do in ES5. Example :

const methods = ['info', 'warm', 'debug', 'error', 'fatal']

class Logger {
    constructor(name) {
        this._name = name;
    }
    get name() {
        return this._name
    }
    set name(name) {
        this._name = name
    }
}

methods.forEach((method) => {
    Logger.prototype[method] = function (event) {
        const tags = {
            event,
            id: uuidv1(),
            level: method.toUpperCase(),
            timestamp: Date.now()
        }

        console.log(tags)
    }
})
Fathy
  • 4,939
  • 1
  • 23
  • 25