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[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[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 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 '' : 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)));
}

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
