简体   繁体   中英

can't understand ".this" in mongoose virtual


userSchema.virtual("password")
      .set(function(password) {
          //temp var
          this._password = password;

          //gen salt
          this.salt = this.makeSalt();

          //encrypt pass
          this.hashed_password = this.encryptPassword(password);

      })
      .get(function () {
          return this._password;
      });


     
   



i want to know the scope the "this" is refering to in the above code.i got a mongo schema called userSchema for which i am setting up a virtual field ie password.Just curious about what the this refers to here as normally inside a function call this refers to the global scope.

This is referring to the target field.

On a side note if you are trying to encrypt the password I would go with “pre” instead of a virtual to store the encrypted password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM