Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are functions like escape, unescape, etc, not methods on the String object? [closed]

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?

like image 523
Darth Egregious Avatar asked May 15 '12 13:05

Darth Egregious


2 Answers

Because they are specific to the browser environment. They don't have a place in the generic String object for the JavaScript language.

like image 83
Quentin Avatar answered Sep 23 '22 12:09

Quentin


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

like image 27
Andrew Avatar answered Sep 25 '22 12:09

Andrew