gpt4 book ai didi

javascript - 在模型验证中获取 this.id 返回 undefined

转载 作者:行者123 更新时间:2023-11-30 13:57:41 24 4
gpt4 key购买 nike

我在字段的验证中将 this 设置为 undefined,但即使我在 Sequelize.define 的第三个参数中设置,也会发生同样的情况使用其他字段作为 documentation描述。

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);
}
}
}
);

}

在这段代码中,console.log 输出undefined undefined。如果我使用密码验证,对于 this.id 仍然得到 undefined,但通过参数接收密码。我一直在寻找解决方案,但这似乎是一个罕见的问题,只找到了 this abandoned issue在 GitHub 上。有没有其他方法可以获取this.id

Sequelize 版本 4.42.0

最佳答案

您没有理解“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

关于javascript - 在模型验证中获取 this.id 返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com