杂种模式方法或原型函数



我对功能和ES6类有一个问题。我不确定从猫鼬架构创建的新对象是否复制了每个新对象的功能。最好的方法是使用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 & beyond/ch3.md#classes

来自eS6

中原型的等效。

类语法或多或少只是构造函数的句法糖 功能 原型。IE。结果(几乎)等于

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

//ES6样式

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

两者都是等效的

最新更新