JavaScript: Breaking all rules

Source: Internet
Author: User
Tags chrome developer chrome developer tools javascript eval

Angus Croll, a front-end engineer from Twitter, gave a speech entitled "Break all the Rulez" at the JSConf conference in Berlin. I mainly talked about some things that we generally think are wrong and should not be used. They are actually useful. The lecture (Link) used by Angus Croll, the father of JavaScript, who is far away in the United States, also agreed to most of the ideas (it seems that there is still a problem ?).
Below I will give a brief translation of the key points, without further explanation.

With statement
Why not use it?
1. Unexpected running results may implicitly create global variables
2. excessive consumption of closure scope resolution
3. Post-Compilation
Some people say that ES5's strict mode can prevent the implicit creation of global variables (without var), which can reduce the issue of...
The strict mode cannot use with either.
Why is it useful?
1. Build a browser developer Tool
 
// Chrome Developer Tools
IS. _ evaluateOn =
Function (evalFunction, obj, expression ){
IS. _ ensureCommandLineAPIInstalled ();
Expression =
"With (window. _ inspectorCommandLineAPI ){\
With (window) {"+ expression + "}}";
Return evalFunction. call (obj, expression );
}
2. Simulate block-level scope
 
// Yes, it's still an old problem.
Var addHandlers = function (nodes ){
For (var I = 0; I <nodes. length; I ++ ){
Nodes [I]. onclick =
Function (e) {alert (I );}
}
};
 
// You can use a function to solve this problem
Var addHandlers = function (nodes ){
For (var I = 0; I <nodes. length; I ++ ){
Nodes [I]. onclick = function (I ){
Return function (e) {alert (I );};
} (I );
}
};
 
// Or use 'with' to simulate block-level scope
Var addHandlers = function (nodes ){
For (var I = 0; I <nodes. length; I ++ ){
With ({I: I }){
Nodes [I]. onclick =
Function (e) {alert (I );}
}
}
};
Eval statement
Why not use it?
1. Code Injection
2. Closure optimization is not possible.
3. Post-Compilation
Why is it useful?
1. When JSON. parse is unavailable
Someone said on Stack Overflow:
"JavaScript eval is insecure. Use the JSON parser on json.org to parse JSON"
Some people say:
"Do not use eval to parse JSON! Json2.js written by Douglas !"
However:
 
// From JSON2.js
 
If (/^ [\], :{}\ s] * $/
. Test (text. replace (/* regEx */,'@')
. Replace (/* regEx */, ']')
. Replace (/* regEx */,''))){
J = eval ('+ text + ')');
}
2. The JavaScript console of the browser is implemented using eval.
Execute the following code in the Webkit console or JSBin.
 
> (Function (){
Console. log (String (arguments. callee. caller ))
})()
 
Function eval (){
[Native code]
}
John Resig said:
"Eval and with are despised, misused, and publicly condemned by most JavaScript programmers, but if they can be used correctly, they can be used to write out some wonderful, code that cannot be implemented using other functions"
Function Constructor
Why is it useful?
1. Code runs within the foreseeable Scope
2. Only global variables can be dynamically created.
3. There is no closure Optimization Problem
Where is it used?
1. parseJSON of jQuery
 
// JQuery parseJSON
 
// Logic borrowed from http://json.org/json2.js
If (rvalidchars. test (data. replace (rvalidescape ,"@")
. Replace (rvalidtokens, "]")
. Replace (rvalidbraces ,""))){
 
Return (new Function ("return" + data ))();
}
2. Underscore. js string Interpolation
 
// From _. template
 
// If a variable is not specified,
// Place data values in local scope.
If (! Settings. variable)
Source = 'with (obj | {}) {\ n' + source + '} \ n ';
 
//..
 
Var render = new Function (
Settings. variable | 'obj ',' _ ', source );
= Operator
Why not use it?
1. Forcibly convert the operands on both sides to the same type
Why is it useful?
1. Forcibly convert the operands on both sides to the same type
2. undefined = null
 
// Is it difficult to write data like this?
If (x = null) | (x = undefined ))
 
// You can write as follows:
If (x = null)
3. When the operand types on both sides are obviously used at the same time
 
Typeof thing = "function"; // The typeof operator must return a string.
MyArray. length = 2; // The length attribute must return a number.
MyString. indexOf ('x') = 0; // The indeOf method returns a number.
The true value is not necessarily = true, and the false value is not necessarily = false
 
If ("potato "){
"Potato" = true; // false
}
Array Constructor
Why not use it?
1. Is new Array () also edevil? JSLint is also recommended [].
Why is it useful?
 
// From prototype. js extension
// String. prototype
Function times (count ){
Return count <1?
'': New Array (count + 1). join (this );
}
'Me'. times (10); // "mememememememememe"
Others
Do not extend native prototype objects
(Es 5 shims)
HasOwnProperty is always used in the for/in time
(It is not necessary to do so without the extension object prototype)
Place all var statements on the top
(The for statement should still be placed in the initialization expression)
Declare a function before calling a function.
(Used when implementation details are given priority)
Do not use the comma Operator
(It can be used when multiple expressions are used)
When parseInt is used, the second parameter is always set to 10.
(Unless the string starts with '0' or 'X', it is unnecessary)
Translator's note
As mentioned above, I also think of a misunderstanding, that is, escape. Many people on the Internet say, "Do not use escape ".
Why is it useful?
1. escape has more escape characters. Sometimes, the last two functions must be escaped.
ASCII char escape () encodeURI () encodeURIComponent ()
! % 21! !
# % 23 # % 23
$ % 24 $ % 24
& % 26 & % 26
'% 27''
(% 28 ((
) % 29 ))
+++ % 2B
, % 2C, % 2C
/// % 2F
: % 3A: % 3A
; % 3B; % 3B
= % 3D = % 3D
? % 3F? % 3F
@ % 40
~ % 7E ~ ~
2. Convert the string to UTF8 encoding, which is usually used in base64.
Escape is equivalent to converting utf16 encoded strings. encodeURIComponent is equivalent to converting utf16 strings into utf8 encoding before escape.
EncodeURIComponent (str) === escape (UTF16ToUTF8 (str ))
You can export UTF16ToUTF8 (str) = unescape (encodeURIComponent (str)
It is much easier to use base64 encoding than to see on the Internet. Note that btoa and atob are compatible.
 
Function base64Encode (str ){
Return btoa (unescape (encodeURIComponent (str )));
}
 
Function base64Decode (str ){
Return decodeURIComponent (escape (atob (str )));
}
 
 

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.