簡體   English   中英

使用箭頭函數時未定義的虛擬字段貓鼬

[英]Undefined virtual field mongoose when using arrow function

我是 mongoDB 的新手。

這是我的架構:

const userSchema = new mongoose.Schema({
    firstName:{
        type:String,
        required:true,
        //remove whitespaces
        trim:true,
        //minimum length
        min:3,
        max:20
    },
    lastName:{
        type:String,
        required:true,
        trim:true,
        min:3,
        max:20
    }
})

一切都很好,直到這里。但現在我想創建一個虛擬財產,因此這樣做了:

//virtual property
userSchema.virtual('fullName').get(()=>{
    console.log("first name " + this.firstName);
    return this.firstName + " " + this.lastName;
});

this收益undefined ,因為this是空的。 但是當我使用普通的function關鍵字來創建函數時,它解決了這個問題。 arrow函數不綁定this嗎?

發生這種情況是因為您使用的 ES6 箭頭函數無法綁定 'this',因為 'this' 已經綁定。 更多關於此主題的信息 => 使用箭頭函數理解 javascript 中的“this”

嘗試使用普通的函數關鍵字,如下所示

userSchema.virtual('fullName').get(function () {
  console.log("first name " + this.firstName);
  return this.firstName + " " + this.lastName;
});

在此處輸入圖片說明

在 JavaScript ES6 中。 箭頭函數沒有上下文。 this關鍵字指向窗口對象。 如果要使用this關鍵字,請使用function name(){}

暫無
暫無

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

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