Home >Web Front-end >JS Tutorial >JavaScript breaks all the rules

JavaScript breaks all the rules

高洛峰
高洛峰Original
2016-11-26 14:32:331448browse

Angus Croll, a front-end engineer from Twitter, gave a speech titled "Break all the Rulez" at the JSConf conference in Berlin. Mainly talking about some things that we usually think are wrong and should not be used, but are actually useful. The lecture notes (link) used by Angus Croll for his speech, the father of JavaScript in the United States, after reading it, agreed with most of the views (seems there are still problems?).
I will briefly translate the key points below without further explanation.

with statement
Why not use it?
1. Unexpected running results, global variables may be created implicitly
2. Closure scope resolution consumes too much
3. Post-compilation
Some people say that ES5’s strict mode can prevent Implicitly creating global variables (without using var) can reduce a problem with with. But...
You cannot use with in strict mode.
Why is it useful?
1. Build browser developer tools

// Chrome Developer Tools
IS._Evaluateon =
Function (EvalFunction, Obj, Expression) {
is._ensureCommandLineapIINSTALLED (); w._inSpectorCommandlineapi) {
With (Window) {" + Expression +"}} ";
Return evalFunction.call(obj, expression);
}
2. Simulate block-level scope

//Yes, it’s still this old problem
var addHandlers = function(nodes) {
for (var i = 0; i < nodes.length; i++) {
nodes[i].onclick =
function(e) {alert(i);}
}
};

//You can solve it by wrapping a function outside
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 Go use it?
1. Code injection
2. Cannot perform closure optimization
3. Post-compilation
Why is it useful?
1. When JSON.parse is not available
Someone said on Stack Overflow:
" JavaScript's eval is unsafe, use the JSON parser on json.org to parse JSON"
Some people also said:
"Don't use eval to parse JSON! Use json2.js written by Douglas!"
But:

/ / From JSON2.js

if (/^[],:{}s]*$/
.test(text.replace(/*regEx*/, '@')
.replace(/*regEx*/, ']')
.replace(/*regEx*/, ''))) {
j = eval('(' + text + ')');
}
2. The browser's JavaScript console is all used eval implementation
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 openly condemned by most JavaScript programmers, but if used correctly, you can use them to write Some wonderful code that cannot be implemented with other functions"
Function constructor
Why is it useful?
1. The code runs within a foreseeable scope
2. Global variables can only be created dynamically
3. There is no closure Where is the issue of package optimization
used?
1. jQuery’s parseJSON

// 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. String interpolation of Underscore.js

//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. Force the operands on both sides to be converted to the same type
Why is it useful?
1. Force the operands on both sides to be converted to the same type
2. undefined == null

//Isn’t it troublesome to write like this?
if ((x === null) || (x === undefined))

//You can write it like this
if (x == null )
3. Use when the operand types on both sides are obviously the same

typeof thing == "function"; //The typeof operator will definitely return a string
myArray.length == 2; //The length attribute will definitely return a number
myString .indexOf('x') == 0; //The indeOf method will definitely return a number
True value may not necessarily ==true, false value may not necessarily==false

if ("potato") {
"potato" == true ; //false
}
Array constructor
Why not use it?
1.new Array() is also evil? JSLint also recommends using [].
Why is it useful?

//From prototype.js extension of
//String.prototype
function times(count) {
return count < 1 ?
'' : new Array(count + 1).join(this);
}
'me'.times(10); //"memememememememememe"
Others
No Extend the native prototype object
(es 5 shims all do this)
Always use hasOwnProperty during for/in traversal
(There is no need to do this without extending the object prototype)
Put all var statements at the top
(It is better to put the for statement in the initialization expression)
Declare the function before calling the function
(Use when implementation details are given priority)
Do not use the comma operator
(Can be used when using multiple expressions )
Always specify the second parameter as 10 when using parseInt
(Unless the string starts with '0' or 'x', it is not necessary)
Translator's Note
So much has been said above, I also thought of one myself The thing that is misunderstood is escape. Many people on the Internet say: "Don't use escape".
Why is it said to be useful?
1. escape escapes more characters, and sometimes the last two functions need to be escaped. Unescaped characters.
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, usually used in base64.
escape is equivalent to a string encoded in utf16 Escape, encodeURIComponent is equivalent to converting the utf16 string into utf8 encoding first and then escape.
encodeURIComponent(str) === escape(UTF16ToUTF8(str))
It can be deduced that UTF16ToUTF8(str) === unescape( encodeURIComponent (str)
Then it can be used in base64 encoding, which is much simpler than those seen on the Internet. Note that btoa and atob have compatibility issues.

function base64Encode(str) {
return btoa(unescape(encodeURIComponent(str )));
}

function base64Decode(str) {
return decodeURIComponent(escape(atob(str)));
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn