JavaScript parseint Big Transformation _javascript Skill

Source: Internet
Author: User
Also vaguely remember learned the ins and outs, for oneself mastered an experience and cheered.

Still vaguely remember being tortured by this same problem countless times, helpless and painful determination of the state of mind.

First of all, I must thank those who, even though I have stressed countless times on this issue, have repeatedly repeated similar mistakes.
Without the encouragement of their repeated mistakes, perhaps I will not seriously consider the solution to this problem.
Secondly, we must thank the author and translator of the JavaScript Advanced program design.
Here I get the inspiration to solve the problem, or I still have to emphasize what should be paid attention to when using parseint.


At the same time, I hope to not only leave a solution here.
The ideas and ideas for solving problems, and the experience of extrapolate of the problem are preserved here.

Problem:
The problems that occurred a long time ago do not want to be painful memories.
The problem this time is very simple. Two months of comparison, because the month is extracted from the string, and then converted with parseint.
Results after parseint ("08") The result is 0
For reasons, see the following "JavaScript Advanced Programming" 19~20 page to explain the parseint function.

The parseint () method also has a base pattern that converts binary, octal, hexadecimal, or any other string of strings into integers.
The base is specified by the second parameter of the parseint () method, so to parse the hexadecimal value, you call the parseint () method as follows:
Copy Code code as follows:

var iNum1 = parseint ("AF", 16); Return 175

Of course, for binary, octal, or even decimal (default mode), you can call the parseint () method like this:
Copy Code code as follows:

var iNum1 = parseint ("10", 2); Return 2
var iNum2 = parseint ("10", 8); Return 8
var iNum3 = parseint ("10", 10); Return 10

If the decimal number contains a leading 0, it is best to use cardinality 10 so that you do not accidentally get the octal value. For example:

var iNum1 = parseint ("010"); Return 8
var iNum2 = parseint ("010", 8); Return 8
var iNum3 = parseint ("010", 10); Return 10

In this code, two lines of code parse the character "010" into a number.

The first line of code regards this string as a octal value, parsing it in the same way as the second line of code (the Declaration cardinality is 8). The last line of code declares a cardinality of 10, so the iNum3 finally equals 10.

Preliminary skill:
The previous solution was to let everyone discard the parseint function and replace it all with parsefloat.
But as a person, "who can not forget?"
The best way is to preserve the "parseint" of the parseint and to scrap the "God" of it.
So I thought about the "JavaScript Advanced Programming" 87~88 page about "redefining existing methods."
3.6.2 Redefine existing methods
Just as you can define a new method for an existing class, you can redefine an existing method.
As described in the previous chapter, a function name is simply a pointer to a function, so it can be easily pointed to other functions. What happens if you modify the local method, such as toString ()?

Function.prototype.toString = function () {
Return "Function code hidden";
}
The preceding code is completely legitimate and the results of the operation are entirely in line with expectations:
function Sayhi () {
Alert ("Hello!") ");
}
Alert (sayhi.tostring ()); Output "Function code hidden"
Perhaps you remember that the ToString () method of the function in the 2nd chapter usually outputs the source code of the functions.
Overriding this method, you can return another string (in this case, return "Function code hidden").
But what about the original function that toString () points to? It will be recycled by the garbage collector because it is completely discarded.
There is no way to restore the original function, so the pointer to store it is safe for later use before overwriting the original method.
You may even invoke the original method in a new method in some cases:
Function.prototype.originalToString = Function.prtotype.toString;
Function.prototype.toString = function () {
if (this.originaltostring (). Length >100) {
Return ' Function too leng to display. '
} else {
return this.originaltostring ();
}
In this code, the first line of code puts an argument to the current toString () method

Used in property originalto-string. The ToString () method is then overwritten with a custom method.
The new method checks whether the function source code is longer than 100.
If it is, it returns an error message stating that the function code is too long, otherwise calling the Originaltostring () method returns the source code of the function.

According to this example, as long as divert writes a line
Global.prototype.parseInt = Global.prototype.parseFloat;
So the parseint function really becomes a façade, the belly is doing is the function of parsefloat activities.
But at the same time a fatal problem point is also in sight.
That's the global object in JavaScript, just like God, it's a concept.
Note See the instructions for "built-in objects" on page 70 of JavaScript advanced programming below.
The global object is the most specific object in the ECMAScript because it does not actually exist at all.
If you try to write the following code, you get an error:
var pointer = Global;
The error message shows that global is not an object, but was it not that global was an object?
That's right. The main concept to understand here is that there is no independent function in ECMAScript, and all functions must be methods of an object.
The functions described earlier in this book, such as isNaN (), Isfinite (), parseint (), and parsefloat (), all look like independent functions.
In fact, they are all methods of the global object.

So, surf the internet to find out how to get global object, or how to use Global.prototype to change parseint function.
The result can be imagined, God is God, even the famous "Search God net" Google also can't find out.
Want to give up the time, sure enough should be the sentence of "death and epigenetic." It suddenly occurred to me that parseint was like a global function, with no object calls at all.
That is not to say, as long as the above sentence changed to parseint = parsefloat;
Sure enough, God, everywhere!!! Good!!!.


Deep and exquisite:
The problem is basically solved. The only thing to note is that the JavaScript load fails, and the following statements do not load.
So this sentence must be put in the first sentence of execution. Now it's time to build a JavaScript generic method library that requires each page to be introduced to the library file later.
So this sentence is placed in the first line of the JavaScript common method library, and you can rest easy.
But when I write a comment about the code, especially when I enumerate how to apply it, I find the following code problem
Alert (parseint ("010", 2)); 10
Alert (parseint ("010", 8)); 10
Alert (parseint ("010", 10)); 10
Each processing returns a value of 10, that is, can handle binary, octal, hexadecimal parseint disappeared.
If the parseint of a single parameter has caused a lot of trouble, we still want to retain its psychic powers for the parseint of the two parameters that do not have a problem.
Further improvements are therefore required.
Then it is necessary to use the parseint function, the number of passing parameters to judge processing.
If there is only one argument, then the parsefloat is called to return the result.
If there are more than two parameters, then the processing of the parseint two parameters is invoked, and the result is returned.
To determine the number of parameters used in the arguments object, see the JavaScript Advanced Program Design 53~54 page about the arguments object description.
In function code, using special object arguments, developers can access them without explicitly pointing to parameter names.
For example, in the function Sayhi (), the first argument is the message.
Arguments[0] Also accesses this value, which is the value of the first parameter (the first argument is at position 0, the second is at position 1, and so on).
Therefore, you can override a function without explicitly naming the argument:
function Sayhi () {
if (arguments[0] = = "Bye") {
Return
}
Alert (arguments[0]);
}
So you have the following code:
Originalparseint = parseint;
parseint = function () {
if (arguments.length = = 1) {
Return parsefloat (Arguments[0]);
} else {
Return Originalparseint (Arguments[0], arguments[1]);
}
In this code we have modified the parseint to handle it differently by the number of parameters.
With a new variable Originalparseint retains the prototype of the parseint.
In this way, even if we transform the parseint, we can still use the original function of parseint through the retained prototype variable Originalparseint.

Innocence
Code written to this thought everything OK, but was said to completely erase the parseint function on the 2, 8 processing.
Think about it too. Too extreme to deal with, just want to use parsefloat completely replace the annoying parseint function.
If we are using a 2-or 8-in-number conversion, we have to originalparseint the new variant of the parseint function that we struggled to preserve.
In fact, our wish is very simple.
The parseint function only has one parameter to allow it to simply handle the 10 conversion, and stop making some headaches for the first 0来.
When we use the second parameter and want it to handle 2, 8, I still have the ability to use parseint.
So there's the following final code:
Take into account the volume of JS files, to minimize the amount of code. So the originalparseint replaced the $parseInt.
In addition to the super long built-in object name arguments directly into a letter a so that the object of 4 times to save the amount of code is very significant.


Extrapolate
The reconstruction of the parseint function is done.
In fact, we can, based on the experience of this transformation, transform JavaScript methods with similar annoying features as parseint.
For example, Escape,unescape, a method that has been deprecated by a consortium of organizations, can be replaced with the recommended method

escape = encodeURI;
unescape = decodeURI;
So based on this experience, in the future encountered similar problems can be taken into account with this great diversion of the way to solve.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.