JavaScript Pristine reading notes (1,2) _javascript tips

Source: Internet
Author: User
Tags case statement control characters inheritance object model reserved terminates hasownproperty
1th Chapter Essence
Some of the features of JavaScript feature a lot more trouble than they are worth. Some of these features are because the specification is so imperfect that it can cause portability problems; Some features can lead to the generation of code that is difficult to understand and modify; some features make my Code style too complex and error-prone, and some features are design errors. Sometimes the designer of a language can make mistakes.
Most programming languages have the essence and the part of the chicken. I found that if I only used the essence to avoid using the ribs, I could be a better programmer. After all, how can you build a good thing with bad parts?
It would be almost impossible for the standards Committee to remove the defective part of a language because it would damage all the bad programs that depended on the chicken parts. They are usually powerless to accumulate more features in the presence of a large number of defects. And the new and old features do not always coexist harmoniously, and may thus produce more parts of the ribs.
But you have the right to define your own subset. You can simply write a better program based on the essence. The proportion of the chicken in JavaScript is more than expected. In the short to the astonishing time, it never existed to develop to the global adoption. It has never been tried and polished in the lab. When it is still very rough, it is directly integrated into Netscape's Navigator 2 browser. With the failure of JAVATM's small application (Java applets), JavaScript has become the default Web language. As a programming language, the popularity of JavaScript is almost entirely unaffected by its quality.
Fortunately, JavaScript has some very elite parts. The most essential part of JavaScript is so deeply hidden that the mainstream view of it over the years is that JavaScript is an ugly, useless toy. The purpose of this book is to reveal the essence of JavaScript so that you know it is an outstanding dynamic programming language.
Perhaps the best part of learning the essence is that you don't have to think about the ribs. It's very difficult to forget about bad patterns. It's a very painful job and most of us will be very reluctant to face it. Sometimes, a subset of languages is developed to enable students to learn better. But here, the JavaScript subset I've developed is for the main professional to work better.
1.1 Why use JavaScript
JavaScript is an important language because it is the language of a Web browser. Its combination with browsers makes it one of the most popular programming languages in the world. At the same time, it is one of the most despised programming languages in the world. The browser's API and Document Object Model (DOM) are pretty bad, causing the JavaScript to be unfairly blamed.
JavaScript is the most despised language, because it is not the so-called mainstream language. If you're good at some of the mainstream languages, but you're programming in a JavaScript-only environment, it's pretty annoying to be forced to use JavaScript. Most people don't think it's necessary to learn JavaScript first, but they will be surprised to find that JavaScript is very different from the mainstream language they prefer to use, and these differences are crucial.
The amazing thing about JavaScript is that you can use it to do your job in situations where you don't know much about the language and even don't know much about programming. It is a language with strong expressive power. When you know what to do, it can even perform better. Programming is a very difficult thing to do. You should never start your work when you know nothing about it.
1.2 Analyzing JavaScript
JavaScript is built on some very good ideas and a few very bad ideas.
Those very good ideas include functions, weak types, dynamic objects, and an expressive literal notation. Those bad ideas include a programming model based on global variables.
JavaScript functions are (primarily) top-level objects based on lexical scopes (lexical scoping). JavaScript is the first lambda language to become a mainstream. In fact, JavaScript has more in common with Lisp and scheme than Java. It's a lisp with a C coat. This makes JavaScript a very powerful language.
Strong typing is popular in most programming languages today. The principle is that a strong type allows the compiler to detect errors at compile time. The sooner we can detect and fix bugs, the less we'll pay. JavaScript is a weakly typed language, so the JavaScript compiler cannot detect a type error. On the other hand, the weak type is actually free. We don't have to build complex times, I never do coercion type conversions, and I don't have to be tired of coping with type systems to get the desired behavior.
JavaScript has a very powerful representation of object literals. By listing the components of an object, they can be simply created. This notation produces a popular format for Data interchange (--json).
Prototype inheritance is a controversial feature in JavaScript. JavaScript has a classless (Class-free) object system in which objects inherit properties directly from other objects. This is really powerful, but for those who are trained to use classes to create objects, prototype inheritance is a strange concept. If you try to apply a class based design pattern directly to JavaScript, you will suffer setbacks. But if you learn to use JavaScript's archetypal nature, your efforts will be rewarded.
JavaScript is criticized for choosing key ideas. Although in most cases these choices are appropriate. But one option is pretty bad: JavaScript relies on global variables to connect. All top-level variables for all compilation units are set to a common namespace called global objects. This is a bad thing, because global variables are demons, and they are fundamental in JavaScript.
In a few cases, we cannot overlook the part of the ribs. There are also some unavoidable dross that we will point out when it comes to these parts. If you want to learn about the chicken parts and how to use them poorly, see any other JavaScript books.
JavaScript is a language with many differences. It contains a lot of errors and sharp corners (sharp edges), so you might wonder: "Why do I use JavaScript?" "There are two answers. The first one 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 has failed in the browser environment. The booming of JavaScript just shows that JavaScript does have its merits.
The other answer is that although JavaScript is flawed, it's really good. It is both lightweight and expressive. And once you've mastered it, you'll find that functional programming is a fun thing to do.
But in order to better use the language, you must know its limitations. I will reveal them mercilessly. Don't be discouraged by it. The essence of the language is enough to make up for the inadequacy of its ribs.
1.3 A simple test ground
If you have a Web browser and any text editor, you have everything you need to run a JavaScript program. First, create an HTML file that can be named program.html:
Copy Code code as follows:

<body>
<pre>
<script src= "Program.js" ></script>
</pre>
</body>

Next, in the same folder, create a script file that can be named Program.js:
Document.writeln (' Hello, world! ');
Next, use your browser to look up your HTML files to see the results. This book will use a method to define the new method. Here's how it's defined:
Copy Code code as follows:

Function.prototype.method=function (Name,func) {
This.prototype[name]=func;
return this;
}

I'll explain it in the 4th chapter.
2nd Chapter Grammar
This chapter describes the syntax for the essence of JavaScript and briefly outlines its language structure.
2.1 Blank
Whitespace may appear as a format character or as a form of annotation. Whitespace is usually meaningless, but occasionally it is necessary to separate the sequence of characters, otherwise they are merged into a single symbol. For example, for the following code:
var that = this;
The spaces between Var and that cannot be removed, but other spaces can be removed.
JavaScript provides two annotation forms, one is a block annotation surrounded by/*//, and the other is a line comment that starts with//. Annotations should be fully used to improve the readability of the program. It is important to note that the annotation must accurately describe the code. Comments that are not used are worse than no annotations.
The block annotation form enclosed with/*/* * comes from a shorthand called pl/i (Silence: Programming Language one). The "I" is actually the "one" of Roman numerals, the language of the third generation of advanced programming languages invented by IBM in the 1850s. In JavaScript,/* may appear in regular expression literals, so block annotations are unsafe for annotated blocks of code. For example:
/*
var rm_a =/a*/.match (s);
*/
A syntax error has been caused. Therefore, I recommend that you avoid using the/*//comment and replace it with//comment.
2.2 Identifiers
An identifier begins with a letter and optionally adds one or more alphanumeric or underscores. 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 have not been used in this language. This list does not include words that should have been retained without reservation, such as Undefined, Nan, and infinity. JavaScript does not allow reserved words to be used to name variables or parameters. Worse, JavaScript does not allow you to use reserved words as the object's property name in object literals or after a property accesses the expression's point number.
Identifiers are used for statements, variables, parameters, property names, operators, and tags.
2.3 Numbers
JavaScript has only a single numeric type. It is represented internally as a 64-bit floating-point number, like a double in Java. In JavaScript, 1 and 1.0 are the same values.
If there is an exponential portion of a number literal, the value of the literal is computed by the second part of the section before e multiplied by 10 E. So 100 and 1e2 are the same number.
Negative numbers can be composed of prefix operators.
A value Nan is a numeric value that represents a result of an operation that does not produce a normal result. Nan is not equal to any value, including itself. You can use function isNaN (number) to detect Nan.
The value infinity represents all values greater than 1.79769313486231570e+308.
Number-owning method (see chap. 8th). JavaScript has an object, math, that contains a set of methods that work with numbers. For example, you can use the Math.floor (number) method to convert a digit to an integer.
2.4 String
String literals can be enclosed in single or double quotes, which may contain 0 or more characters. \ is an escape character. When JavaScript is created, Unicode is a 16-bit character set, so all characters in JavaScript are 16-bit.
JavaScript has no character type. To represent a character, you only need to create a string that contains only one character.
The escape character allows you to insert characters that are normally not allowed into a string, such as backslashes, quotes, and control characters. The \u convention allows you to specify the character code bits that are represented by numbers.
"A" = = = "\u0041"
The string has a Ength property. For example, "seven". Length is 5.
The string is immutable. Once the string is created, it can never be changed. But it's easy to get a new string by using the + operator to connect to other strings. Two strings that contain exactly the same characters and have the same character order are considered to be the same string. So:
' C ' + ' a ' + ' t ' = = ' Cat '
Is true.
There are some methods of string (see chap. 8th).
2.5 Statements
A compilation unit contains a set of executable statements. In a Web browser, each <script> tag provides a compiled unit that compiles and executes immediately. Because of the lack of linker, JavaScript throws them together into a common global namespace. Appendix A has more information about global variables.
When the Var statement is used inside the function, it defines the private variable of the function.
The switch, while, for, and do statements allow an optional Front label (label) to be used with the break statement.
Statements are often executed in order from top to bottom. JavaScript can change this execution sequence by using conditional statements (if and switch), circular statements (while, for and do), forced jump statements (break, return, and throw), and function calls.
A code block is a set of statements wrapped in a pair of curly braces. Unlike in many other languages, code blocks in JavaScript do not create a new scope, so variables should be defined at the top of the function, not in the code block.
The IF statement alters the control flow of the program based on the value of the expression. If the value of the expression is true, then the then code block is executed, otherwise an optional else branch is executed.
The values listed below are treated as false:
Fase
Null
Undefined
Number 0
Number Nan
All other values are treated as true, including True, string "false", and all objects.
The switch statement executes a multilink branch. It matches the value of its expression with all specified case conditions. Its expression may produce a number or string. When an exact match is found, the statement in the matching case clause is executed. If no match is found, an optional default statement is executed.
A case clause consists of one or more case expressions. Case expressions do not necessarily have to be constants. To prevent the next Case,case statement from continuing, you should follow a forced jump statement. You can use the break statement to exit a switch statement.
The while statement performs a simple loop. If the expression value is false, then the loop terminates. And when the expression value is true, the code block is executed.
A For statement is a circular statement that is more complex in structure. There are two forms of it.
The common form is controlled by three optional clauses: the initialization clause (initialization), the conditional clause (condition) and the increment clause (increment). First, the initialization clause is executed, and its function is usually to initialize the loop variable. Then the value of the conditional clause is calculated. Typically, it detects a loop variable based on a completion condition. If the conditional clause is omitted, the return condition is assumed to be true. If the value of the conditional clause is false, then the loop terminates. Otherwise, the code block is executed, then the increment clause is executed, then the loop repeats the conditional clause.
Another form (called A For in statement) enumerates all the property names (or key names) of an object. In each loop, another property name string for the object is assigned to the variable between for and in.
Usually you have to detect object.hasownproperty (variable) to determine whether the property name is a member of the object or is found from its prototype chain.
Copy Code code as follows:

for (MyVar in obj) {
if (Obj.hasownproperty (MyVar)) {
...
}
}

A do statement is like a while statement, the only difference being that it detects the value of an expression after the code block executes rather than before. This means that the code block will always be executed at least once.
The Try statement executes a block of code and captures any exceptions thrown by the code block. The catch clause defines a new variable that will receive the exception object.
The throw statement throws an exception. If the throw statement is in a try block, then control jumps to the catch clause. If the throw statement is in a function, the function call is discarded, and control jumps to the catch clause of the try statement that called the function.
An expression in a throw statement is usually an object literal that contains a Name property and a message property. The exception grabber can use this information to determine what to do.
The return statement causes a person function to be returned in advance. It can also specify the value to be returned. If no return expression is specified, the return value is undefined.
JavaScript does not allow wrapping between the return keyword and an expression.
The break statement causes the program to exit a loop statement or a switch statement. It can specify an optional label that will cause the program to exit the statement with that label.
JavaScript does not allow wrapping between the break keyword and the label.
A expression statement can assign a value to one or more variables or members, call a method, or remove an attribute from an object. operator = is used to assign values. Do not confuse it with the identity operator = = = =. operator + = can be used for addition operations or connection strings.
2.6-expression
Ternary operator? There are three counts. If the first operation value is true, it produces the value of the second operand. However, if the first operand is false, it produces the value of the third operand.
Table 2-1: Operator precedence
. []()
Attribute access and function calls
Delete New typeof +-!
Unary operator
*/%
Multiplication, division, modulo
+-
addition/connection, subtraction
>= <= > <
Inequality operator
=== !==
Equality operator
&&
Logic and
||
Logical OR
?:
Ternary
The values produced by the TYPEO operator are ' number ', ' String ', ' Boolean ', ' undefined ', ' function ', ' object '. If the OP count is an array or null, then the result is ' object ', which is wrong. There will be more information on TypeOf in chapters 6th and Appendix A.
/operator may produce a non-integer result, even if the two operands are integers.
A function call raises the execution of a function. The function call operator is a pair of parentheses following the function name. Parentheses may contain arguments that will be passed to this function. In the 4th chapter there will be more content about functions.
A property access expression is used to specify an object or an array of properties or elements. I'll describe it in detail in the next chapter.
2.7 Literal Amount
Object literals are a notation that makes it easy to specify new objects. The property name can be an identifier or a string. These names are treated as literal names rather than variable names, so the object's property name is known at compile time. The value of the property is an expression. The next chapter will have more information about the literal volume of objects.
The literal amount of an array is a notation for conveniently specifying a new array. The 6th chapter will have more content on the literal volume of the array.
In the 7th chapter there will be more content about regular expressions.
The function literal defines the function value. It can have an optional name for recursively calling itself. It can specify a list of parameters that will be initialized as a variable by the actual argument (arguments) that is passed when it is invoked. The body of a function includes variable definitions and statements. In the 4th chapter there will be more content about functions.

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.