Getting this.id on model validation returns undefined

问题: I'm getting this as undefined on field's validate, but the same occurs even if I set in third argument of Sequelize.defineto use other fields as documentation describes....

问题:

I'm getting this as undefined on field's validate, but the same occurs even if I set in third argument of Sequelize.defineto use other fields as documentation describes.

module.exports = function (sequelize, DataTypes) {

const User = sequelize.define(
    'User', 
    {...}, //all fields here
    {
        freezeTableName: true,
        paranoid: true,
        validate: {
            isPasswordRepeated: () => {
                console.log(this.id, this.password);
            }
        }
    }
);

}

In this code, console.log outputs undefined undefined. If I use on password's validate, still gets undefined for this.id, but receives password through argument. I've looked for solutions, but it seems a rare problem and only found this abandoned issue on GitHub. Is there another way to get this.id?

Sequelize version 4.42.0


回答1:

You're not understanding the context of 'this'.

Inside a function, the value of this depends on how the function is called.

...

Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.

...

In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context

  • 发表于 2019-07-08 00:26
  • 阅读 ( 274 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除