我正在学习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中使用Classes
到目前为止,我有 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))
}
})
}
谢谢!
答案 0 :(得分:0)
ES6类(大多数)是JavaScript OOP模型的语法糖。您仍然可以像在ES5中那样修改原型。示例:
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)
}
})