我是 JS 初学者,最近遇到了这段代码。 该函数怎么可能影响结果? 接下来我不太明白的是该函数刚刚定义,它被直接调用( pet.toJSON() <<< 这样的东西)。那么它怎么可能有效呢?我想问的最后一件事是:该函数的名称是什么,或者我应该在网上查找什么来了解它。 如果这是显而易见的事情,我很抱歉,但您的回答会对我有很大帮助。 祝你有美好的一天!
const pet = {
name: 'Marek'
}
pet.toJSON = function () {
return {}
}
console.log(JSON.stringify(pet)) // the result is {}
userSchema.methods.toJSON = function () {
const user = this
const userObject = user.toObject()
delete userObject.password
delete userObject.tokens
return userObject
}
最佳答案
What kind of JavaScript function is
<object>.<somefunction>
?
完全正常的方法。
Why does it influence the object without direct calling?
它是直接调用的,只是通过您没有编写且没有查看的代码来调用。
JSON.stringify
的内部结构检查名为 toJSON
的方法对象并调用它(如果存在)。
If the value has a toJSON() method, it's responsible to define what data will be serialized.
或者the specification (更具体地说 this part of it ):
- Let toJSON be Get(value, "toJSON").
- ReturnIfAbrupt(toJSON).
- If IsCallable(toJSON) is true
- Let value be Call(toJSON, value, «key»).
关于javascript - <object>.toJSON(....) 是什么样的 JavaScript 函数?为什么不直接调用就影响对象呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56967605/