【发布时间】:2018-08-21 19:57:42
【问题描述】:
我正在学习 JavaScript/Node,我发现了一种在 ES5 中从数组创建函数的方法,但在 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)
}
})
所以当我打电话时
log.fatal('fatal error')
以正确的方式打印 我想做一点点相同的事情,但在 ES6 中使用类
到目前为止,我有 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))
}
})
}
谢谢!
【问题讨论】:
-
您应该能够像以前一样在
class上执行相同的循环。class无论如何都会编译成原型......它只是语法糖。
标签: javascript node.js ecmascript-6