JavaScript breaks all the rules
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)));
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
