gpt4 book ai didi

JavaScript/NodeJs - 类型错误 : Cannot set property 'validation' of undefined

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:51 26 4
gpt4 key购买 nike

我想验证用户表单输入,我只是编写了这段代码,但实际上有一个错误我无法修复,我不明白为什么它在这里(错误)。

let User = (data) => {
this.data = data
this.errors = []
}
User.prototype.validation = () => {
if(this.data.username == ""){
this.errors.push("You must* provide a username")
}else if(this.data.email == ""){
this.errors.push("You must* provide the email address for you account")
}else if(this.data.password == ""){
this.errors.push("You must* provide the password for your account")
}
}
User.prototype.register = () => {
// step #1 validate user data
this.validation()
// step #2 only if there are no validation errors
// then save the user data into a database
}

module.exports = User

以及我得到的错误。

User.prototype.validation = () => {
^

TypeError: Cannot set property 'validation' of undefined
at Object.<anonymous> (C:\Users\40sherrin\Desktop\application\models\User.js:5:27)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\Users\40sherrin\Desktop\application\controllers\userController.js:1:76)
at Module._compile (internal/modules/cjs/loader.js:689:30)

最佳答案

您不能对 defining a constructor function 使用箭头函数.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

原型(prototype)属性的使用

Arrow functions do not have a prototype property.

let User = function (data) {
this.data = data
this.errors = []
}
User.prototype.validation = function() {
if(this.data.username == ""){
this.errors.push("You must* provide a username")
}else if(this.data.email == ""){
this.errors.push("You must* provide the email address for you account")
}else if(this.data.password == ""){
this.errors.push("You must* provide the password for your account")
}
}
User.prototype.register = function() {
// step #1 validate user data
this.validation()
// step #2 only if there are no validation errors
// then save the user data into a database
}

因此请使用 function 或 ES6 类。


class User {

constructor(data) {
this.data = data
this.errors = []
}

validation() {
// ...
}

register() {
this.validation();
}
}

关于JavaScript/NodeJs - 类型错误 : Cannot set property 'validation' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59344601/

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