我想验证用户表单输入,我只是编写这段代码,但实际上有一个我无法修复的错误,我也不明白为什么它在这里(错误)。
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. (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. (C:\Users\40sherrin\Desktop\application\controllers\userController.js:1:76) at Module._compile (internal/modules/cjs/loader.js:689:30)
defining a constructor function不能使用箭头功能。
箭头函数表达式在语法上紧凑于 正则函数表达式,尽管没有自己的绑定 this,arguments,super或new.target关键字。 箭头功能 表达式不适合用作方法,因此不能用作 构造函数。
使用原型属性
箭头功能没有原型属性。
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(); }} ,
fat arrow functions do not have prototypes。
【文章转自:扬州机房 http://www.558idc.com/yz.html欢迎留下您的宝贵建议】