【问题标题】:ES6 Method from an array [duplicate]来自数组的ES6方法[重复]
【发布时间】: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


【解决方案1】:

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)
    }
})

【讨论】:

  • 完美!这就是我要找的!谢谢@fathyb
  • 不要忘记,您必须使用 new 运算符构造 class 才能使其工作
  • 简单的方法,但不起作用。 //logger.js ... module.exports = Logger//index.js var l = new Logger() console.log(l) // Logger { _name: undefined } console.log(l.prototype) //undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 2019-06-14
  • 1970-01-01
  • 2016-07-11
  • 2017-11-07
相关资源
最近更新 更多