Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

javascript - Does every object in JS have a toString() method?

enter image description here

enter image description here

If that is true, why this error happens? The req.body object is not null or undefined as the picture shows.

I use the node-inspector to debug my express.js app, this picture is taken in Chrome Developer Tools.

Express configuration:

app.use(express.bodyParser())

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:

enter image description here

How to re-sign a proper toString method?

I tried delete the undefined toString, no good. See:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does every object in JS have a toString() method?

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.

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.

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).

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"; };

but probably you want the standard one:

req.body.toString = Object.prototype.toString;

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...