JS 中的每个对象都有 toString() 方法吗? [英] Does every object in JS have a toString() method?
问题描述
如果这是真的,为什么会发生这个错误?req.body
对象不是 null
或 undefined
如图所示.
If that is true, why this error happens? The req.body
object is not null
or undefined
as the picture shows.
我使用 node-inspector
来调试我的 express.js
应用,这张照片是在 Chrome Developer Tools
中拍摄的.
I use the node-inspector
to debug my express.js
app, this picture is taken in Chrome Developer Tools
.
快速配置:
app.use(express.bodyParser())
感谢您的评论,现在我发现 req.body
是 undefined
,但新问题是如何使 toString
再次工作?我希望 req.body.toString()
返回如下字符串:
Thanks to your comments, now I found the req.body
is undefined
, but new question is how to make the toString
works again? I want req.body.toString()
to return string as below:
如何重新签署一个合适的toString
方法?
How to re-sign a proper toString
method?
我试过delete
未定义的toString
,不行.见:
I tried delete
the undefined toString
, no good. See:
推荐答案
JS 中的每个对象都有 toString() 方法吗?
Does every object in JS have a toString() method?
没有.只有那些从 Object.prototype
继承它(就像所有普通对象一样)或自己定义它(或从他们的自定义原型继承它)的人这样做.
No. Only those that inherit it from Object.prototype
(as all normal objects do) or define it on its own (or inherit it from their custom prototype) do.
你可以通过Object.create(null)
来创建这样不寻常的对象.你也可以给一个普通对象一个自己的 toString
属性,它隐藏继承的一个而不是一个函数(例如 {toString:0}
),但我想那会'我抛出了一个明显的错误.
You can create such unusual objects by Object.create(null)
. You also could give a plain object an own toString
property that shadows the inherited one and is not a function (e.g. {toString:0}
), but I guess that would've throw a distinct error.
在您的情况下,bodyParser()
确实(确实)创建了没有原型的对象,以避免在使用此类参数时修改 .constructor.prototype
.参见 qs pullrequest #58 和 express 问题 1636:Bodyparser 未设置 object.prototype?(建议更新).
In your case, it seems that the querystring parser used by bodyParser()
does (did) indeed create objects without prototypes, to avoid mangling .constructor.prototype
when such parameters were used. See qs pullrequest #58 and express issue 1636: Bodyparser not setting object.prototype? (suggesting an update).
如何重新分配一个合适的 toString 方法?
How to reassign a proper toString method?
你可以分配任何函数,比如
You could just assign any function, like
req.body.toString = function() { return "Hi, I'm a request body"; };
但可能你想要标准的:
req.body.toString = Object.prototype.toString;
其他选项是通过非标准的 __proto__
属性(req.body.__proto__ = Object.prototype
)重新定义原型,或者简单地在对象而不是使其成为方法,例如 Object.prototype.toString.call(req.body)
.
Other options would be redefining the prototype via the non-standard __proto__
property (req.body.__proto__ = Object.prototype
) or simply applying a standalone function on the object instead of making it a method, like Object.prototype.toString.call(req.body)
.
这篇关于JS 中的每个对象都有 toString() 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!