Javascript: itoa , atoi prototype - Convert an integer to ASCII character by extending JS String Object

A very convenient way in JavaScript exists to extend and map functions.
Note: A true shortcoming of the language in today's Browsers is the intentional truncation of operator overloading in browser-JavaScript implementations, which will be discussed shortly. There are many situations where the conversion of a character into an integer, representative of  its decminal form within the ASCII symbol table, and the conversion from the symbol into the decimal form is necessary.
Be aware that the following functions can mostly deal only with printable ASCII characters (i.e. dec 32-162) in older Brosers. There is also a way to extend that range in characters to yield true binary output of any encoding, allowing dynamic generation of any file-type which a particular Internet Browser is able to process.
In order to understand the following code examples, some knowledge about Javascript's prototype is advisable. If you are familiar with the concept, skip the following Note.

Note: In javascript everything, even a function, is an descendant from the Object prototype. This is why you can write code such as (4.5).toFixed() which validates and interprets perfectly fine, returning in this case "5". This superobject class means that all other descendant classes such as String, and Number, - which was just used in the previous example-, inherit many import methods with it. For instance, when declaring a new Object-class the extending class (as the parent class) overrides the constructor property, own toString, and valueOf methods, among others. (toString  is automatically called whenever ObjectClassA + ObjectClassA is executed by the JS-Interpreter).
Unless the respective prototype functions are overriden, the respective prototype function will be invoked in a hierarchical manner, propagating down the prototype-chain. This chain is an hierarchy of overridden functions which follow the Object's inheritance. As such, String is a direct descendant from Object. The most important feature of prototype lies in the use to extend even instanced Objects! with methods and properties which they previously did not possess. To understand what this means in practice it is best to learn from the examples provided below. It is useful to perform these yourself on an interactive JavaScript interpreter ( STRG+SHIFT+I  in Chrome ).


String.prototype.itoa = String.fromCharCode;
function fromCharCode() { [native code] }
"".itoa(25)
" "
"".itoa(35)
"#"
"".itoa(75)
"K"
"".itoa(126)
"~"
"".itoa(130)
""
String.itoa(100)

TypeError
String.itoa
undefined
String.itoa = String.fromCharCode;
function fromCharCode() { [native code] }
String.itoa(100)
"d"
delete String.itoa
true
String.itoa(100)

TypeError
x = new String("me")

String
x.itoa(100)
"d"
copy and past the code below to use this in your own code: continued...


LihatTutupKomentar