简体   繁体   English

在模型验证中获取this.id返回未定义

[英]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.define to use other fields as documentation describes. 我在字段的validate上将this作为undefined ,但是即使我在Sequelize.define第三个参数中Sequelize.define为使用其他字段作为文档描述, Sequelize.define发生同样的情况。

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 . 在此代码中, console.log输出undefined undefined If I use on password's validate, still gets undefined for this.id , but receives password through argument. 如果我使用密码的验证,则this.id仍未undefined ,但通过参数接收密码。 I've looked for solutions, but it seems a rare problem and only found this abandoned issue on GitHub. 我一直在寻找解决方案,但这似乎是一个罕见的问题,仅在GitHub上发现了这个被遗弃的问题 Is there another way to get this.id ? 还有另一种方式来获取this.id吗?

Sequelize version 4.42.0 Sequelize版本4.42.0

You're not understanding the context of 'this'. 您不了解“ 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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