我正在尝试学习express,并想将ES6与babel一起使用。我的问题是当我使用静态方法来处理如下请求时;
class MyCtrl {
static index (req,res) {
res.status(200).send({data:"json data"});
}
}
router.get('/', MyCtrl.index)
我想知道,这(使用静态方法)会影响性能吗?我对 Node.js 运行时了解不多,但据我所知,在某些语言(如 C#)中频繁使用静态方法并不是一件好事。
或者是否有另一种正确的方法来使用 ES6 类来执行此操作。
最佳答案
ES6 类并不是真正的新结构,它只是 JavaScript 原型(prototype)模型的一些语法糖。
所以当你做这样的事情时:
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 的原型(prototype)东西。因此,就您的问题而言,您所做的就是将常规函数传递给 router.get ,因此不存在任何性能差异。
关于javascript - ES6 Express 和静态方法使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855478/