this series as effective JavaScript 's reading notes.
in the JavaScript , a function object exists on the toString method, which makes it easy to return the source code of a function to a string object.
(function (x) {return x + 1;}). ToString (); "Function (x) {\ n return x + 1;\n}"
toString method will not only let some hackers find the method of attack, but also the method has serious limitations.
First, toString method is not implemented in a way that is ECMAScript normalized, so various JavaScript In the execution engine. toString may not be implemented in an inconsistent way.
Second, when toString can return the function source code and the function itself is completely JavaScript when implemented, the source code is returned correctly. For example, in the following function call, using the bind method to get a new function object ( about how bind is used, you can refer to Item (+):
(function (x) {return x + 1;}). Bind (+). toString (); "Function (x) {\ n [native code]\n}"
It can be found that one of the returned strings is [Nativecode] , which is because in many JavaScript in the execution environment, Bind methods are used in other programming languages, such as C + + to achieve. So see native code here actually represents a compiled C + + source code.
Finally, toString the source code returned by the method does not reflect the value of the passed parameter:
(function (x) {return function (y) {return x + y;}}) (). toString (); "Function (y) {\ n return x + y;\n}"
the parameters passed in the above code the is not reflected in the returned function source code.
because of these limitations, the toString methods are difficult to use correctly and reliably. In practical applications, you should avoid using it as much as possible.
Summarize:
- ECMAScript The standard does not have a function toString implementation of the code.
- because toString There are inconsistent behaviors on various platforms and try not to use them.
Effective JavaScript Item 28 do not rely on the ToString method of the function