A string could be seen as the simplest object that can hold and manipulate text, and as such functions that act on strings should not necessarily be lumped in as methods. On the other hand, javascript is primarily a web programming language, and working with URIs is quite a common use for strings in the language; in this case something like lastName.encodeURIComponent()
would actually be quite useful.
Why things like encodeURIComponent and unescape are functions and not methods on the String object? Is there some CS principle at work here, or was it a subjective choice by one of the designers of the language?
Obviously not every function that operates on a string needs to be in the string object, but where and how do people decide where to draw the line?
Because they are specific to the browser environment. They don't have a place in the generic String object for the JavaScript language.
I don't think those methods are part of JavaScript but are inherited from window
, which is the global object associated with browsers. Thus, while the functions you listed deal with strings, they're actually closely bound to browser function and thus aren't attached to the String
prototype. Sources like MDN are sort of murky on this but I'm pretty sure that the original JS spec makes no mention of these methods.
It maybe didn't make much sense, but nowadays it actually is conceivable that someone might want to use JS as the language of an embedded system or something else that has no Internet association. Here, a syntax that included encodeURIComponent()
would be as out of place as document.getElementById()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With