Javascript 带有原型而非函数的mongoose模型构造函数
我从瓦莱里·卡尔波夫的《掌握猫鼬》一书中了解了猫鼬。 他陈述如下Javascript 带有原型而非函数的mongoose模型构造函数,javascript,node.js,mongoose,prototypal-inheritance,Javascript,Node.js,Mongoose,Prototypal Inheritance,我从瓦莱里·卡尔波夫的《掌握猫鼬》一书中了解了猫鼬。 他陈述如下 // Calling `conn.model()` creates a new model. In this book // a "model" is a class that extends from `mongoose.Model` const MyModel = conn.model('ModelName', schema); Object.getPrototypeOf(MyModel) === mong
// Calling `conn.model()` creates a new model. In this book
// a "model" is a class that extends from `mongoose.Model`
const MyModel = conn.model('ModelName', schema);
Object.getPrototypeOf(MyModel) === mongoose.Model; // true
我不明白一个类,正如我所理解的,它是一个构造函数,怎么会有一个原型,而不是“function.prototype”。(我指的是实际的原型,而不是原型属性)
为了明确MyModel是一个类/构造函数,他继续这样使用它:
const document=new MyModel()代码>
我已经回顾了我对javascript中protoypal继承的理解,没有任何东西能够解释这一点
谁能解释一下这里发生了什么。我的困惑来自这样一个事实,即我从未意识到es6类中如何实现继承与“我”如何使用构造函数实现继承之间有细微的区别
这篇文章帮助我找到了我需要知道的:
借用文章中的例子:
如果我们用这样的构造函数实现继承
function Hero(name, level) {
this.name = name
this.level = level
}
// Adding a method to the constructor
Hero.prototype.greet = function () {
return `${this.name} says hello.`
}
// Creating a new constructor from the parent
function Mage(name, level, spell) {
// Chain constructor with call
Hero.call(this, name, level)
this.spell = spell
}
// Creating a new object using Hero's prototype as the prototype for the newly created object.
Mage.prototype = Object.create(Hero.prototype)
console.log(Object.getPrototypeOf(Mage))// logs - ƒ () { [native code] }
没有理由期望mage的原型不是-ƒ(){[本机代码]}
事实并非如此
但是,使用类时,有些事情是在引擎盖下完成的,我不知道:
class Hero {
constructor(name, level) {
this.name = name
this.level = level
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`
}
}
// Creating a new class from the parent
class Mage extends Hero {
constructor(name, level, spell) {
// Chain constructor with super
super(name, level)
// Add a new property
this.spell = spell
}
}
console.log(Object.getPrototypeOf(Mage)) // logs the hero constructor
每个类都扩展了mongoose。Model
继承自Model
类本身(从术语上讲继承自函数。prototype
),另请参见