我创建了一个UserSchema
并添加了一个方法,我尝试在其中设置它的属性name
:
import mongoose, { Schema } from 'mongoose'
const UserSchema = new Schema({
name: String
})
UserSchema.methods.setName = (name) => {
this.name = name + '123'
}
exports default mongoose.model('User', UserSchema)
我导入了对象并从我创建的 Controller 中调用了方法:
import User from './User'
exports.signup = (request, response) => {
const name = 'Ignas'
const UserModel = new User
UserModel.setName(name)
...
}
由于某种原因,它向我抛出一个错误:
TypeError: Cannot set property "name" of undefined
this
怎么可能是未定义的?
如果我修改传递对象的方法,我可以让它按我想要的方式工作,但它看起来又脏又不正确,因为我想做的就是通过它的方法更改对象的属性..
// modified method of Schema
UserSchema.methods.setName = (User, name) => {
User.name = name + '123'
}
// modified call from the controller
UserModel.setName(name)
最佳答案
箭头函数不绑定(bind)自己的this
。他们使用词汇 this
。箭头函数按词法绑定(bind)其上下文,因此 this
实际上指的是原始上下文。这称为词法作用域。词法作用域的含义是什么:
Lexical scoping (sometimes known as static scoping ) is a convention used with many programming languages that sets the scope (range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined.
您可以在 MDN 中找到有关此问题的更多说明。例如。
最后,它会寻找 this
在所有父级上下文中,直到找到它为止,在您的情况下,因为在模块中没有 this
的定义任何地方,返回undefined
。
关于javascript - Express.js Mongoose : TypeError Cannot set property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902367/