Javascript extract Reading Notes (1, 2)

Source: Internet
Author: User
Tags case statement hasownproperty

From: http://student.csdn.net/space.php? Uid = 45106 & Do = Blog & view = me

Chapter 2 Some of the essential JavaScript features bring much more trouble than they do. Some of these features may cause portability problems due to imperfect specifications. Some features may cause problems that are hard to understand and modify. Code Some features make my code style too complex and error-prone; some features are design errors. Sometimes Language designers make mistakes. Majority Programming Language Both have the essence and chicken ribs. I found that if I only use the essence and avoid using the chicken ribs, I can become a better Program Member. After all, how can we build good things with bad parts? It is almost impossible for the Standards Committee to remove the defective part of a language, because doing so will damage all bad programs that depend on those chicken ribs. In addition to accumulating more features on a large number of existing defects, they are usually powerless. In addition, new and old features do not always coexist harmoniously, which may lead to more chicken ribs. However, you have the right to define your own subset. You can write better programs based on the essence. The proportion of chicken ribs in Javascript exceeds expectation. In a very short time, it never evolved into a global adoption. It has never been tried and polished in the lab. When it is still very rough, it is directly integrated into the navigator 2 browser of the net scene. As Java applets fails, JavaScript becomes the default web page language ". As a programming language, the popularity of JavaScript is almost completely unaffected by its quality. Fortunately, JavaScript has some excellent parts. The most essential part of JavaScript is deeply hidden, so that the mainstream view of JavaScript over the years is that JavaScript is an ugly and 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 benefit of learning the essence is that you don't have to consider the chicken ribs. It is very difficult to forget a bad model. This is a very painful job, and most of us are reluctant to face it. Sometimes, a subset of languages is made to help students learn better. But here, I have developed a javascript subset to better serve the primary professional. 1.1 Why JavaScript? Javascript is an important language because it is a Web browser language. Its combination with browsers makes it one of the world's most popular programming languages. It is also one of the world's most despised programming languages. The browser's API and Document Object Model (DOM) are rather bad, leading to unfair JavaScript criticism. Javascript is the most despised language, because it is not the so-called mainstream language. If you are good at programming in some mainstream languages, but in an environment that only supports JavaScript, it is quite annoying to be forced to use JavaScript. Most people think it is unnecessary to learn JavaScript first, but they are surprised to find that JavaScript is very different from the mainstream languages they prefer to use, and these differences are critical. The amazing thing about Javascript is that you can use it to do your work without much understanding of the language or even programming. It is a language with strong expressiveness. When you know what to do, it can even do better. Programming is very difficult. You should never start your work when you know nothing about it. 1.2 Analyze Javascript Javascript is built on some very good ideas and a few very bad ideas. Good ideas include functions, weak types, dynamic objects, and an expressive literal representation. Bad ideas include programming models based on global variables. JavaScript Functions are top-level objects (mainly) based on lexical scoping. Javascript is the first mainstream Lambda language. In fact, JavaScript has more in common with lisp and scheme than Java. It is a lisp with a C coat. This makes JavaScript a very powerful language. Nowadays, many programming languages require strong types. The principle is that a strong type allows the compiler to detect errors during compilation. The earlier we can detect and fix errors, the less we will pay. Javascript is a weak language, so the Javascript compiler cannot detect type errors. On the other hand, the weak type is actually free. We don't need to create complex times, I never need to force type conversion, and we don't have to cope with the type system to get the desired behavior. Javascript has a very powerful representation of object literal. By listing the components of objects, they can be simply created. This representation produces the popular data exchange format-JSON. Prototype inheritance is a controversial feature in JavaScript. Javascript has a class-free object system in which objects directly inherit attributes from other objects. This is really powerful, but prototype inheritance is a strange concept for programmers who are trained to use classes to create objects. If you try to apply the class-based design pattern directly to Javascript, you will suffer setbacks. However, if you learn the prototype nature of using JavaScript, your efforts will be rewarded. Javascript has been criticized for its choice of key ideas. Although in most cases, these options are appropriate. However, there is a bad choice: javascript depends on global variables for connection. All top-level variables of all compilation units are combined into a public namespace called a 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 chicken ribs. In addition, there are some inevitable dregs. When these components are involved, we will point them out. If you want to learn about the chicken ribs and how to use them poorly, see any other JavaScript books. Javascript is a language with many differences. It contains many errors and sharp edges, so you may wonder: "Why do I need JavaScript ?" There are two answers. First, you have no choice. Web has become an important application development platform, and JavaScript is the only language that can be recognized by all browsers. Unfortunately, Java fails in the browser environment. The vigorous development of JavaScript just shows that JavaScript is indeed extraordinary. The other answer is that JavaScript is excellent despite its flaws. It is lightweight and expressive. And once you have mastered it, you will find functional programming very interesting. But to better use this language, you must know its limitations. I will reveal them relentlessly. Don't be discouraged. The essence of this language is enough to make up for its shortcomings. 1.3 A simple test ground If you have a web browser and any text editor, you have everything you need to run javascript programs. First, create an HTML file named program.html: <HTML> <Body> <PRE> <SCRIPT src = "program. js"> </SCRIPT> </PRE> </Body> </Html> Next, create a script file in the same folder and name it program. JS: Document. writeln ('hello, world! '); Next, use your browser to open your HTML file and view the result. This book always uses a method to define a new method. The following is its definition: Function. Prototype. method = function (name, func ){ This. Prototype [name] = func; Return this; } I will explain it in chapter 4th. Chapter 2 This chapter introduces the syntax of the essential part of JavaScript and briefly introduces its language structure. 2.1 Blank Blank spaces may be formatted characters or comments. White spaces are usually meaningless, but occasionally need to be used to separate character sequences, otherwise they will be merged into a single symbol. For example, for the following code: VaR that = this; Spaces between VaR and that cannot be removed, but other spaces can be removed. Javascript provides two types of Annotations: block comments enclosed by/**/and line comments starting. Annotations should be fully used to improve program readability. Note that annotations must accurately describe the code. Comments that are useless are worse than those without comments. In the form of block annotations enclosed ( Talk silently:Programming Language one. "I"Is actually the" one "of the Roman numerals. It isIBMCompany in19Century50The third-generation advanced programming language invented in the age . In JavaScript, */may appear in the regular expression literal, so block comments are insecure for the commented block. For example: /* VaR rm_a =/A */. Match (s ); */ A syntax error occurs. Therefore, we recommend that you do not use/**/annotation instead of // annotation. 2.2 Identifier An identifier starts with a letter and can be selectively followed by one or more letters, numbers, or underscores. The following reserved words cannot be used for identifiers: abstractboolean break bytecase catch char class const limit default Delete do doubleelse Enum export extendsfalse final float for partition implements import in instanceof int limit new limit private protected limit static super switch limit throw throws transient true try typeofvar volatile voidwhile with is largely retained in this list The word is not used in this language. This list does not contain words that should be reserved but not reserved, such as undefined, Nan, and infinity. JavaScript does not allow the use of reserved words to name variables or parameters. What's worse, JavaScript cannot use reserved words as the property name of an object in the literal volume of an object, or after the dot of an attribute access expression. Identifiers are used for statements, variables, parameters, attribute names, operators, and tags. 2.3 Number Javascript has only one numeric type. It is represented as a 64-bit floating point number internally, the same as Java's double. In JavaScript, the values 1 and 1.0 are the same. If a numeric literal has an exponential part, the value of this literal is calculated by multiplying the part before E by the power of the part after E 10. So 100 and 1E2 are the same numbers. Negative numbers can be composed by the prefix operator. The value Nan is a numerical value, indicating an operation result that cannot produce normal results. Nan is not equal to any value, including itself. You can use the isnan (number) function to detect Nan. The Infinity value indicates all values greater than 1.79769313486231570e + 308. Digital ownership method (see chapter 1 ). Javascript has an object math, which contains a set of methods that act on numbers. For example, you can use the math. Floor (number) method to convert a number into an integer. 2.4 String The string literal can be enclosed in single quotes or double quotation marks. It may contain 0 or multiple 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 single character, you only need to create a string containing only one character. Escape characters can be inserted into strings that are normally not allowed, such as backslash, quotation marks, and control characters. The \ U Convention allows you to specify the digit number. The "A" = "\ u0041" string has an ength attribute. For example, "Seven". length is 5. The string is unchangeable. Once a string is created, it cannot be changed. However, it is easy to connect other strings through the + operator to obtain a new string. Two strings that contain identical characters and have the same character sequence are considered to be the same strings. Therefore: 'C' + 'A' + 'T' = 'cat' Is true. The string has some methods (see Chapter 8th ). 2.5 Statement A compilation unit contains a set of executable statements. In a Web browser, each <SCRIPT> TAG provides a compilation unit that is compiled and executed immediately. Because the linker is missing, JavaScript will throw them together into a public global namespace. Appendix A has more information about global variables. When a var statement is used inside a function, it defines the private variable of the function. The switch, while, for, and do statements can have an optional label, which is used together with the break statement. Statements are executed in the ascending order. Javascript can change the execution sequence through conditional statements (if and switch), loop statements (while, for, and do), Forced Jump statements (break, return, and throw), and function calls. A code block is a set of statements in a pair of curly braces. Unlike many other languages, code blocks in Javascript do not create a new scope, so variables should be defined at the top of the function, rather than in the code block. The IF statement changes the control flow of the program based on the value of the expression. If the expression value is true, run the then code block. Otherwise, run the optional else branch. Values listed below are treated as false: fasenullundefined number 0 Number Nan all other values are treated as true, including true, string "false", and all objects. The switch statement executes multiple branches. It matches the value of its expression with all specified case conditions. The expression may generate a number or string. When an exact match is found, the statement in the matched case clause is executed. If no matching is found, the optional default statement is executed. A case clause contains one or more case expressions. The case expression is not necessarily a constant. To prevent execution of the next case, the case statement should follow the one-on-one force redirect statement. You can use the break statement to exit a switch statement. The while statement executes a simple loop. If the expression value is false, the loop ends. When the expression value is true, the code block is executed. A For statement is a more complex loop statement. It has two forms. The common form is controlled by three optional clauses: initialization, condition, and increment ). First, the initialization clause is executed, which usually serves to initialize the cyclic variable. Then calculate the value of the Conditional Clause. Typically, it detects cyclic variables based on a completion condition. If the condition clause is omitted, it is assumed that the returned condition is true. If the value of the Condition Clause is false, the loop ends. Otherwise, execute the code block, then execute the incremental clause, and then the loop repeats the conditional clause. The for in statement enumerates all attribute names (or key names) of an object ). In each loop, another property name string of the object is assigned to a variable between for and in. Generally, you must check object. hasownproperty (variable) to determine whether the property name is a member of the object or found from its prototype chain. For (myvar in OBJ ){ If (obj. hasownproperty (myvar )){ ... } } A do statement is like a while statement. The only difference is that it detects the value of the expression after the code block is executed, rather than before. This means that the code block will always be executed at least once. The try statement executes a code block and captures any exceptions thrown by the code block. The catch clause defines a new variable that receives the exception object. Throw an exception. If the throw statement is in a try code block, the control will jump to the catch clause. If the throw statement is in the function, the function call is abandoned, and the control will jump to the catch clause of the try statement that calls the function. The expression in a throw statement is usually an object literal, which contains a name attribute and a message attribute. The exception catcher can use this information to determine what to do. The Return Statement will make one-person function return in advance. It can also specify the value to be returned. If no return expression is specified, the returned value is undefined. JavaScript does not allow line breaks between return keywords and expressions. The break statement causes the program to exit a loop or switch statement. It can specify an optional tag, which will cause the program to exit the statement with this tag. JavaScript does not allow line breaks between break keywords and labels. An expression statement can assign values to one or more variables or members, call a method, or delete an attribute from an object. Operator = is used to assign values. Do not confuse it with constant and other operators =. Operator + = can be used for addition operations or connection strings. 2.6 Expression Ternary operator? There are three operation numbers. If the value of the first operation is true, it generates the value of the second operation. However, if the first operation is false, it will generate the value of the third operation. Table 2-1: Operator priority
. [] () attribute access and function calling
delete new typeof + -! unary operator
*/% multiplication, division, modulo
+- addition/connection and subtraction
=> inequality operators
==! == equality operator
& logic and
|| logical or
? : Sanyuan
The typeo operators generate 'number', 'string', 'boolean', 'undefined', 'function', and 'object' values '. If the number of operations is an array or null, the result is 'object', which is incorrect. Chapter 2 and Appendix A will have more information about typeof. /Operator may generate a non-integer result, even if both arithmetic values are integers. Function invocation triggers function execution. The function call operator is a pair of parentheses following the function name. Parentheses may contain parameters that will be passed to this function. Chapter 2 will provide more information about functions. An Attribute access expression is used to specify the attributes or elements of an object or array. I will describe it in detail in the next chapter. 2.7 Literal Object literal is a representation that allows you to specify a new object. The property name can be an identifier or string. These names are treated as literal names rather than variable names, so the property names of objects can be known during compilation. The attribute value is an expression. The next chapter will show more information about the object literal volume. An array literal is a representation that allows you to easily specify a new array. Chapter 2 will provide more information about the array literal. Chapter 2 will provide more information 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, which will be used as the actual parameters passed by the variable during the call (Arguments) Initialization. The main body of a function includes variable definitions and statements. The4Chapter will show more information 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.