【问题标题】:ES6 Express and static methods usage questionsES6 Express 和静态方法使用问题
【发布时间】:2016-04-26 04:49:18
【问题描述】:

我正在尝试学习 express,并希望将 ES6 与 babel 一起使用。我的问题是当我使用静态方法来处理如下请求时;

class MyCtrl {

   static index (req,res) {
        res.status(200).send({data:"json data"});
    }
}

router.get('/', MyCtrl.index)

我想知道,这(使用静态方法)会影响性能吗?我对 Node.js 运行时了解不多,但我知道在某些语言(如 C#)中经常使用静态方法并不是一件好事。

或者是否有另一种正确的方法来使用 ES6 类来做到这一点。

【问题讨论】:

    标签: javascript node.js express babeljs


    【解决方案1】:

    ES6 类并不是真正的新结构,它只是 JavaScript 原型模型的一些语法糖。

    所以当你做这样的事情时:

    class Animal {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    
      static printAllowedTypes() {
        console.log('Rabbit, Dog, Cat, Monkey');
      }
    
      printName() {
        console.log(`Name: ${this.name}`);
      }
    
      printAge() {
        console.log(`Age: ${this.age}`);
      }
    }
    

    在幕后,它基本上只是翻译成这样:

    function Animal(name, age) {
      this.name = name;
      this.age = age;
    }
    
    Animal.printAllowedTypes = function() {
      console.log('Rabbit, Dog, Cat, Monkey');
    };
    
    Animal.prototype.printName = function() {
      console.log(`Name: ${this.name}`);
    };
    
    Animal.prototype.printAge = function() {
      console.log(`Age: ${this.age}`);
    };
    

    所以这是一个方便的简写,但它仍然只是使用 JavaScript 的原型东西。因此,就您的问题而言,您所做的只是将常规函数传递给router.get,因此没有任何性能差异。

    【讨论】:

    • 谢谢。你的回答很有道理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2019-03-27
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多