簡體   English   中英

我的貓鼬模式中未定義this.name

[英]this.name is undefined in my Mongoose schema

我有問題 在我的kittySchema貓鼬模式中。 第21行,我試圖從架構對象中獲取this.name,但是我不確定。 我知道是什么問題。 我正在使用箭頭函數,並且正在箭頭函數中查找this.name屬性,而不是箭頭函數所在的對象。是否可以使用常規的香草js函數代替我來解決此問題? `

// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}

`

嗯,正如您已經知道的那樣,Arrow函數本身沒有this ,因此您已經遇到了問題,可以做的是將arrow函數包裝在常規函數中:

var myKitty = {
  name: "Majid",
  kittyMethod : function() { 
    return (() => {
        console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
    })();
}
}
myKitty.kittyMethod ();//Mew, My Name is Majid

https://jsfiddle.net/a2ww7tby/

我正在使用箭頭功能,正在箭頭功能中尋找this.name屬性,而不是箭頭功能所在的對象

這個假設是錯誤的。 箭頭函數在詞匯范圍內尋找值。 在這種情況下,它恰好是global對象。

另一方面,如果使用“常規”功能,則“ this”將綁定到實例化新小貓時創建的新對象。

要解決您的問題,只需使用常規功能代替箭頭功能即可。

kittySchema.methods.speak = function() {
    console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
}

無需包裝箭頭功能。

您可以在此處閱讀有關何時不使用箭頭功能的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM