Mongoose模式方法或原型函数?

时间:2017-12-02 03:12:58

标签: javascript node.js mongoose-schema

我对函数和ES6类有疑问。我不确定从mongoose模式创建的新对象是否复制了每个新对象的函数。使用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!')

在决定提出我的第一个问题之前,我已经在堆栈溢出和关闭方面进行了相当多的搜索,但我似乎无法将我的项目与我找到的问题联系起来,所以我写了这些例子以帮助描绘我的问题代替。

这两个例子都运行正常,我只是不确定模式中的函数是否为我创建的每个新对象都重复,我知道将它添加到原型中不会,将它添加到原型中是更好的方法,并使用这样的ES6类吗?

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

更新: 如果有其他人带着相同的问题来到这里,在阅读以下链接之后,我只需点击一下即可。 https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch3.md#classes

1 个答案:

答案 0 :(得分:0)

来自参考Equivalent of Prototype in ES6

  

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

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

};

// es6 style

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

  }
}

两者都是等价的

相关问题