[英]mongoose Model constructor with prototype other than function
我正在從 valeri karpov 的 mongoose 書中了解 mongoose。 他陳述如下。
// 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
我不明白 class 是如何構造函數 function 可以有除“Function.prototype”之外的原型。 (我說的是實際原型而不是原型屬性)
只是為了明確表明 MyModel 是一個類/構造函數,他繼續像這樣使用它:
const document = new MyModel();
我已經回顧了我對 javascript 中 protoypal inheritance 的理解,但沒有任何東西可以解釋這一點。
誰能解釋這里發生了什么。
我的困惑來自於我從未意識到 inheritance 如何在 es6 類中實現與“我”如何使用構造函數實現它之間的細微差別。
這篇文章幫助我找到了我需要知道的: https://www.taniarascia.com/understanding-classes-in-javascript/
借用文章中的例子:
如果我們使用像這樣的構造函數實現 inheritance
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 的原型不是 - ƒ () { [native code] },事實上它不是
但是使用類是在我不知道的情況下完成的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.