Why are functions such as escape, unescape, etc., and not methods for a String object?

A string can be considered as the simplest object that can contain and manipulate text, and since functions that act on strings do not have to be focused as methods. On the other hand, javascript is primarily a web programming language, and working with URIs is a fairly common use for strings in the language; in this case something like lastName.encodeURIComponent() would be really useful.

Why are things like encodeURIComponent and unescape functions and not methods of a String object? Is there some kind of CS principle here, or was it the subjective choice of one of the language developers?

Obviously, not every function that works with a string should be in a string object, but where and how do people decide where to draw a line?

+6
source share
4 answers

I do not think that these methods are part of JavaScript, but inherit from window , which is a global object associated with browsers. Thus, although the functions you specified deal with strings, they are actually closely related to the browser function and thus are not tied to the String prototype. Sources like MDN seem cloudy, but I'm sure the original JS specification doesn't mention these methods.

This may not make much sense, but it is currently possible that someone might want to use JS as an embedded system language or something else that does not have an Internet connection. Here the syntax including encodeURIComponent() would be inappropriate as document.getElementById() .

+3
source

Because they are specific to the browser environment. They do not have a place in the general String object for the JavaScript language.

+7
source

Where would you stay. Strings are unique; by definition, in which you use any method that takes a string as an argument or returns, it must be in the string class.

Equally, it would be wise to have encoding methods that use streams and stream methods that do the encoding.

Would you have fun fast, or would you expand the line by delegating the Encoding class.

+1
source

The escape () function encodes a string .

This m * ake function wraps the string *, so it can be transmitted over any network to any computer that supports ASCII characters.

This function encodes special characters.

Now this function is something specific to strings that are URLs in a browser-based environment, JS as a language does not depend on it.

Thus, when you run escape, unescape also in String will become useless in non-network / URL scripts.

This is why they are part of the Window object .

You want it in a string, you can add it to a String prototype.

+1
source

Source: https://habr.com/ru/post/915797/


All Articles