Mongoose模式方法或原型函数?

我有一个关于函数和ES6类的问题。 我不确定从mongoose模式创build的新对象是否为每个新对象复制函数。 什么是最好的方法是什么时候使用ES6类。 我写了一个相关的例子来说明我的意思。

// models/User.js const mongoose = require('mongoose'); // User Schema const userSchema = new mongoose.Schema({ name: { type: String, required: true, unique: true, }, }); userSchema.methods.say = function testFunc(text){ console.log(`${this.name} said ${text}`) } module.exports = mongoose.model('User', userSchema); 

 // models/Animals.js const mongoose = require('mongoose'); // Animal Schema class Animal extends mongoose.Schema { constructor() { const animal = super({ name: { type: String, required: true, unique: true, }, }); animal.methods.say = this.say; } say(text) { console.log(`${this.name} says ${text}`) } } module.exports = mongoose.model('Animal', new Animal) 

 // First test example const User = require('./models/User'); const john = new User({name: "John"}); const jane = new User({name: "Jane"}); john.say('Dog goes woof.'); jane.say('Cat goes meow.\n'); User.prototype.write = function(text) { console.log(`${this.name} wrote ${text}`); } john.write('There\'s just one sound that no one knows.') jane.write('What does the fox say?\n') // Second test example const Animal = require('./models/Animal'); const fox = new Animal({name: "Fox"}); fox.say('Ring-ding-ding-ding-dingeringeding!'); Animal.prototype.screams = function(text) { console.log(`${this.name} screams ${text}`); } fox.screams('Wa-pa-pa-pa-pa-pa-pow!') 

在决定问我的第一个问题之前,我已经search了很多关于堆栈溢出和closures的问题,但是我似乎无法将我的项目与我发现的问题联系起来,所以我编写了这些示例来帮助描述我的问题。

这两个例子都可以正常工作,我只是不确定模式中的函数是否会被我创build的每个新对象复制,我知道把它添加到原型中并不会,将它添加到原型中是更好的方法,是使用这样的ES6类适当?

提前谢谢你,因为我对这个话题很困惑。

更新:如果有其他人来到这里有同样的问题,阅读以下链接的事情只是为我点击。 https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch3.md#classes

从ref。 ES6原型的等价物

类的语法或多或less只是构造函数+原型的语法糖。 即结果(几乎)相当于

 function User(args) { this.args = args } User.prototype.doSomething = function() { }; 

// es6风格

 Class User(){ constructor(args){ this.args= args }, doSomething(){ } } 

两者相当