Chapter 1 The Essence Some of JavaScript’s features are more trouble than they’re worth. Among them, some features are because the specification is very imperfect, which may lead to portability problems; some features lead to the generation of code that is difficult to understand and modify; some features make my coding style overly complex and error-prone; and some features are just Design errors. Sometimes language designers make mistakes.
Most programming languages have good parts and weak parts. I've found that I can become a better programmer if I only use the good parts and avoid the fluff. After all, how can you build something good out of crappy parts?
It is almost impossible for a standards committee to remove defective parts of a language because doing so would damage all the bad programs that depend on those useless parts. There's usually nothing they can do except pile more features on top of a pile of existing flaws. And new and old features don't always coexist harmoniously, which can lead to more useless parts.
However, you have the power to define your own subsets. You can write better programs based on the best parts. The proportion of useless parts in JavaScript exceeds expectations. It went from non-existence to global adoption in an astonishingly short period of time. It has never been tried and polished in a laboratory. When it was still very crude, it was integrated directly into Netscape's Navigator 2 browser. With the demise of Java applets, JavaScript became the default "web language".As a programming language, JavaScript's popularity is almost entirely independent of its quality.
Fortunately, JavaScript has some very essential parts. The most essential part of JavaScript is deeply hidden, so much so that the mainstream view of it for many years has been that JavaScript is an ugly, useless toy. The purpose of this book is to reveal the essence of JavaScript and let everyone know that it is an outstanding dynamic programming language.
Perhaps the biggest advantage of only learning the essential parts is that you don’t have to think about the useless parts. Unlearning bad patterns is very difficult. This is a very painful job that most of us would be reluctant to face. Sometimes, subsets of a language are developed to allow students to learn better. But here, I've formulated a subset of JavaScript that works better for master professionals.
1.1 Why use JavaScript JavaScript is an important language because it is the language of web browsers. Its integration with browsers has made it one of the most popular programming languages in the world. At the same time, it is also one of the most underestimated programming languages in the world. The browser API and Document Object Model (DOM) are so bad that JavaScript gets an unfair rap.
JavaScript is the most despised language because it is not a so-called mainstream language. If you're good at some mainstream language but are programming in an environment that only supports JavaScript, it can be quite annoying to be forced to use JavaScript. Most people don't feel the need to learn JavaScript first, but they are surprised to find that JavaScript is very different from the mainstream languages they would rather use, and these differences are crucial.
The amazing thing about JavaScript is that you can get things done with it without knowing much about the language, or even programming. It is a language with extremely strong expressive power. It even works better when you know what to do. Programming is difficult. You should never start your work without knowing anything about it.
1.2 Analyzing JavaScript JavaScript is built on some very good ideas and a few very bad ideas.
Those really good ideas include functions, weak typing, dynamic objects, and an expressive literal representation. Those bad ideas include a programming model based on global variables.
JavaScript functions are (mainly) top-level objects based on lexical scoping. JavaScript was the first lambda language to become mainstream. In fact, JavaScript has more in common with Lisp and Scheme than with Java. It's Lisp dressed in C. This makes JavaScript a very powerful language.
Strong typing is a popular requirement in most programming languages today. The idea is that strong typing allows the compiler to detect errors at compile time. The earlier we can detect and fix bugs, the less expensive it will be. JavaScript is a weakly typed language, so the JavaScript compiler cannot detect type errors. On the other hand, weak typing is actually free. We don't have to create complex subsystems, I never have to do casts, and I don't have to juggle the type system to get the behavior I want.
JavaScript has a very powerful object literal representation. Objects can be created simply by listing their component parts. This representation gave rise to the popular data exchange format - JSON.
Prototypal inheritance is a controversial feature in JavaScript. JavaScript has a class-free object system in which objects inherit properties directly from other objects. This is really powerful, but prototypal inheritance is a foreign concept to programmers who are trained to use classes to create objects. If you try to apply class-based design patterns directly to JavaScript, you will suffer frustration. However, if you learn to use JavaScript's prototypal nature, your efforts will pay off.
JavaScript has been criticized for its choice of key ideas. In most cases though, these options are appropriate. But there's one option that's pretty bad: JavaScript relies on global variables for concatenation. All top-level variables of all compilation units are grouped into a common namespace called the global object. This is a bad thing because global variables are the devil and they are fundamental in JavaScript.
In a few cases, we cannot ignore the useless parts. There are also some unavoidable bugs, and we'll point them out when it comes to these parts. If you want to learn about the crappy parts and how to use them poorly, check out any other JavaScript book.
JavaScript is a language with many differences. It contains a lot of bugs and sharp edges, so you may be wondering: "Why do I use JavaScript?" There are two answers. The first is that you have no choice. The Web has become an important application development platform, and JavaScript is the only language that all browsers can recognize. Unfortunately, Java fails in browser environments. The vigorous development of JavaScript just shows that JavaScript does have its advantages.
Another answer is that despite its flaws, JavaScript is really good. It is both lightweight and expressive.And once you get the hang of it, functional programming is a lot of fun.
But in order to use this language better, you must know its limitations. I will reveal them mercilessly. Don't let this discourage you. The best parts of the language more than make up for its weak points.
1.3 A simple proving ground If you have a web browser and any text editor, then you have everything you need to run JavaScript programs. First, please create an HTML file, which can be named program.html:
<br><script src="program.js"></script> <br>
Next, create a script file in the same folder, which can be named program.js:
document .writeln('Hello, world!');
Next, use your browser to open your HTML file to view the results. Throughout this book, a method method will be used to define new methods. The following is its definition:
Function.prototype.method= function(name,func){
this.prototype[name]=func;
return this;
}
I will explain it in Chapter 4.
Chapter 2 Syntax This chapter introduces the syntax of the essence of JavaScript and briefly outlines its language structure.
2.1 White space
White space may appear in the form of formatting characters or comments. Whitespace usually has no meaning, but it is occasionally needed to separate sequences of characters that would otherwise be combined into a single symbol. For example, for the following code:
var that = this;
The space between var and that cannot be removed, but other spaces can be removed.
JavaScript provides two forms of comments, one is a block comment surrounded by /* */, and the other is a line comment starting with //. Comments should be used extensively to improve program readability. It is important to note that comments must accurately describe the code. Useless comments are worse than no comments at all.
The block comment form surrounded by /* */ comes from a language called PL/I (short for Programming Language One). The "I" in it is actually the Roman numeral "one", which is an IBM A third-generation high-level programming language invented by the company in the 1850s). In JavaScript, */ may appear inside a regular expression literal, so block comments are unsafe for the commented block of code. For example:
/*
var rm_a = /a*/.match(s);
*/
results in a syntax error. So, I recommend avoiding /* */ comments and replacing it with // comments.
2.2 Identifiers
Identifiers begin with a letter, optionally followed by one or more alphanumeric or underscore characters. Identifiers cannot use the following reserved words:
abstract
boolean break byte
case catch char class const continue
debugger default delete do double
else enum export extends
false final finally float for function
goto
if implements import in instanceof int interface
long
native new null
package private protected public
return
short static super switch synchronized
this throw throws transient true try typeof
var volatile void
while with
Most of the reserved words in this list are not yet used in this language. This list does not include some words that should be reserved but are not, such as undefined, NaN, and Infinity. JavaScript does not allow reserved words to be used to name variables or parameters. To make matters worse, JavaScript does not allow the use of reserved words as object property names in object literals or after a period in a property access expression.
Identifiers are used in statements, variables, parameters, property names, operators and tags.
2.3 Numbers JavaScript has only a single number type. It is represented internally as a 64-bit floating point number, the same as Java's double. In JavaScript, 1 and 1.0 are the same value.
If a numeric literal has an exponent part, then the value of the literal is calculated by multiplying the part before e by 10 raised to the power of the part after e. So 100 and 1e2 are the same number.
Negative numbers can be formed using the prefix operator -.
The value NaN is a numeric value that represents the result of an operation that cannot produce a normal result. NaN is not equal to any value, including itself. You can detect NaN using the function isNaN(number).
The value Infinity represents all values greater than 1.79769313486231570e 308.
Number ownership method (see Chapter 8). JavaScript has an object Math, which contains a set of methods that operate on numbers. For example, you can use the Math.floor(number) method to convert a number to an integer.
2.4 String
A string literal can be enclosed in single or double quotes, and it may contain 0 or more characters. is an escape character. When JavaScript was created, Unicode was a 16-bit character set, so all characters in JavaScript are 16-bit.
JavaScript has no character type. To represent a character, simply create a string containing only one character.
Escape characters allow characters that are not normally allowed to be inserted into a string, such as backslashes, quotes, and control characters. The u convention allows specifying numerical representations of character code points.
“A”===”u0041”
Strings have an length attribute. For example, "seven".length is 5.
Strings are immutable. Once a string is created, it can never be changed. But it's easy to concatenate other strings with operators to get a new string. Two strings containing exactly the same characters in the same order are considered the same string. So:
‘c’ ‘a’ ‘t’ === ‘cat’
is true.
Strings have some methods (see Chapter 8).
2.5 Statements A compilation unit contains a set of executable statements. In web browsers, each