JavaScript language Essence Note 01

Source: Internet
Author: User
Tags button type hasownproperty

The content is relatively simple, just from the beginning to comb the knowledge of JS

Grammar
Blank
Identifier
Digital
String
Statement

Object
Object literal
Retrieval
Update
Reference
Prototype
Reflection
Enumeration
Delete
Reduce global variable contamination

Grammar

1 blanks

Whitespace may appear as formatted characters or as comments. Whitespace is usually meaningless, but occasionally it must be used to divide the sequence of characters, otherwise they will be merged into a single symbol. For example:

var = this;

The space between Var and that is not removed, and the other spaces can be removed.

JS provides two types of annotations:

    • /* */
    • //

It is recommended to use//, because */* * */In the content to be commented may include characters * * and error, for example:

/*

var rm_a=/a*/.match (s);

*/

2 identifiers

The identifier begins with a letter, and the climate can optionally be prefixed with one or more letters, numbers, 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 extend S false final finally float for function Goto if implements import in instanceof int interface long native new null Packag e private protected public return short static super switch synchronized this throw throws transient true try typeof var V Olatile void and with

These reserved words are similar to reserved words in other languages

Identifiers can also start with the $ and _ symbols (although we do not recommend this)

Identifiers are used for statements, variables, parameters, property names, operators, and identities.

3 numbers

JS has only one single numeric type. It is internally represented as a 64-bit floating-point number. It does not separate the integer type, so 1 and 1.0 are the same values.

If a number literal has an exponential part, then the literal is calculated by multiplying the previous part of E by the second part of the E-10. So 100 and 1e2 are the same numbers.

Negative numbers can be made using operator-to-form.

A value of Nan is a numeric value that represents a result of an operation that does not produce the result of a normal operation. Nan is not equal to any value, including its own.

JS has an object, math, which contains a set of methods for numbers. For example, Math.floor indicates that a number is replaced by an integer.

4 string

A string can be enclosed in single or double quotation marks, which may contain 0 or more characters. \ (backslash) is an escape character. JS at the time of creation, Unicode is a 16 character set, so all the characters in JS are 16 bits.

There is no character type in JS. To represent a character, simply create a character string.

The escape character allows characters inserted into a string that are normally not allowed to be inserted into a string, such as backslashes, quotation marks, and controls. The \u convention allows you to specify a numeric representation of a character code bit.

"A" = = = "\u0041"

The string has a length property. For example: "Seven". Length is 5.

The string is immutable. Once a string is created, it can never be changed. But it is easy to get a new string by using the + operator to concatenate other strings. Two strings that contain the same characters and have the same character order are considered to be the same string. So:

' C ' + ' a ' + ' t ' = = = ' Cat '

Is true.

5 statements

If statement

Iftrue  when executing the code}

The following values are treated as false:

    • False
    • Null
    • Undefinde
    • Empty string "'
    • Number 0
    • Number Nan

All other values are treated as true, including true, the string "false", and all the objects.

Switch statement

Switch (n) { case 1:  1 break  ;  Case 2:  2 break  ; default :    Case   code executed at different time in case 2}

While statement

 while (condition) {code to execute}

For statement

 for (var i=0;i<cars.length;i++) {    + "<br>");}

Do statement

 Do {code to execute}  while (conditions);

Try Statement

Try {// Run code here } Catch (Err) {// handle error here }

Throw statement

<script>functionmyFunction () {Try  {  varX=document.getelementbyid ("Demo"). Value; if(x== "")Throw"Empty"; if(IsNaN (x))Throw"Not a number"; if(X&GT;10)Throw"Too High"; if(x<5)Throw"Too Low"; }Catch(err) {varY=document.getelementbyid ("mess"); Y.innerhtml= "Error:" + Err + "."; }}</script>

Object

The simple types of JS include numbers, strings, Boolean values (True and false), and undefined values. All other values are objects. Numbers, strings, and Boolean "seemingly" objects because they have methods, but they are immutable. The object in JS is a mutable keyed set (keyed collections). In JS, an array is an object, a function is an object, a regular expression is an object, and an object is an object.

Objects are containers for properties, where each property has a name and value. The name of the property can be any string, including an empty string. The value of the undefined property can be any value other than the value of the.

The object in JS is classless. It has no constraints on the name and value of the new property. objects are suitable for collecting and organizing data. Objects can contain other objects, which can be easily represented as a tree or graphic structure.

JS includes a prototype chain feature that allows an object to inherit the properties of another object. Using it correctly can reduce the time and memory consumption of object initialization.

1 Object Literals

An object literal is 0 or more "name/value" pairs enclosed in a pair of curly braces. The object literal can appear where any of the allowed expressions appear.

var empty_object = {}; var stooge = {    "first-name": "Jerome",    "last-name": "Howard"};

The property name can be any string, including an empty string. In object literals, if the property name is a valid JS identifier and is not a reserved word, it is not mandatory to enclose the property name in quotation marks. Therefore, it is necessary to enclose "first-name" in quotation marks, but it is optional to enclose the first_name. Commas are used to separate multiple "name/value" pairs.

The value of the property can be obtained from any expression that includes another object literal. objects can be nested:

var flight = {    "oceanic",    815,    departure: {        "SYD",        "2004-09-22 14:55",        "Sydney"    },    arrival: {        "LAX",        "2004-09-23 10:42",        "Los Angeles"    };

2 Search

To retrieve the values contained in an object, you can use the [] suffix to enclose a string expression in the same way. If the string expression is a constant and it is a valid JS identifier rather than a reserved word, it can be used. notation instead. Priority is given. notation, because it is more compact and more readable.

// "Joe" // "SYD"

If you attempt to retrieve the value of a member element that does not exist, a undefined value is returned.

// undefined // undefined // undefined

|| Operators can be used to populate the default values:

var middle = stooge["Middle-name"] | | "(none)"; var status = Flight.status | | "Unknown";

Attempting to retrieve a undefined value will result in a TypeError exception. This can be avoided by using the && operator.

// undefined // throw "TypeError" // undefined

3 update

The values in the object can be updated by an assignment statement. If the property name already exists in the object, then the value of this property is replaced.

stooge[' first-name '] = ' Jerome ';

If the object does not have that property name before it, the property is extended to the object.

stooge[' middle-name ' = ' Lester' = ' Curly '=' Boeing 777 '= ' overdue ';

4 references

Objects are passed by reference, and they are never copied:

var x == ' Curly '; var nick = stooge.nickname; //Because X and Stooge are references to the same object, Nick is ' Curly ' var a = {}, b = {}, c = {}; // A, B, and C each refer to a different null object a = b = c = {}; // A, B, and C both refer to the same empty object

5 prototypes

Each object is connected to a prototype object, and it can inherit properties from it. All objects created by object literals are connected to Object.prototyoe, the standard object in this JS.

When you create a new object, you can select an object as its prototype. We add a Create method to object. This create method creates a new object that uses the prototype object as its prototype.

if (typeof object.create!== ' function ') {    function  (o) {        var  function  () {};         = o;         return New F ();    };} var another_stooge = object.create (stooge);

The prototype connection is not functional at the time of the update. When we make a change to an object, we don't touch the prototype of that object:

another_stooge[' first-name ' = ' Harry '; another_stooge[' middle-name '] = ' Moses '= ' Moe ';

The prototype connection is only used when retrieving values. If we try to get a property value for an object that does not have this property name, JS tries to get the property value from the prototype object. If the prototype object also does not have this attribute, then look in its prototype, and so on, until the procedure finally reaches the end of Object.prototype. If the desired attribute does not exist in the prototype chain at all, the result is the undefined value. This procedure is called a delegate.

A prototype relationship is a dynamic relationship. If we add a new attribute to the prototype, the property is immediately visible to all objects based on that prototype.

Stooge.profession = ' actor'//  ' actor '

6 Reflection

It is easy to examine an object and determine what properties it has, just try to retrieve the property and verify the obtained value.

The typeof operator is useful for determining the type of a property:

typeof // ' number ' typeof // ' String ' typeof // ' object ' typeof // ' undefined '

It is important to note that any attribute in the prototype chain also produces a value:

typeof // ' function ' typeof // ' function '

There are two ways to handle these unwanted properties. First, let your program retrieve and reject the function values. In general, the goal of reflection is data, so you should be aware that some values may be functions.

Another method is to use the hasOwnProperty method, which returns true if the object has a unique property. The hasOwnProperty method does not check the prototype chain.

// true // false

7 Enumeration

The for in statement iterates through all the property names in the object. The enumeration process lists all the properties-including the ones in the function and the prototypes you don't care about-so it's necessary to filter out the values you don't want. The most common filtering is the hasOwnProperty method, and the use of typeof to exclude functions.

var name;  for inch Another_stooge) {    if (typeof Another_stooge[name]!== ' function ') {        + ': ' + Another_ Stooge[name]);}    }

The order in which property names appear is indeterminate, so be prepared for any order that might occur. If you want to ensure that a property appears in a specific property, the best bet is to avoid using the for in statement altogether, instead of creating an array in which to include the property name in the correct order:

var i; var properties = [                ' first-name '                ,                ' middle-name ', ' Last-name ',                 ' profession '                ];  for (i = 0; i < properties.length; i + = 1)    {+ ': ' +    another_stooge[properties[i]]);}

We can get the properties we want through for instead of for, without worrying about discovering the properties in the prototype chain, and we get their values in the correct order.

8 Delete

The delete operation can delete an object's properties. It deletes the properties that are determined in the object. It does not touch any object in the prototype chain.

Deleting an object's properties may cause the properties in the prototype chain to emerge:

// ' Moe ' // removes Another_stooge's nickname property, exposing the nickname property of the prototype Delete  //  ' Curly '

9 Reducing global variable contamination

JS can arbitrarily define the global variables that can hold all the application resources. Unfortunately, global variables weaken the flexibility of the program, and all should be avoided.

One way to minimize the use of global variables is to create only one global variable in your application:

var myapp={};

This variable is now your application container:

Myapp.stooge = {    "first-name": "Joe",    "last-name": "Howard"= {    " Oceanic ",    815,    departure: {        " SYD ",        " 2004-09-22 14:55 ",         "Sydney"    },    arrival: {        "LAX",        "2004-09-23 10:42",         "Los Angeles"    };

As long as you organize multiple global variables into a single namespace, you will significantly reduce the likelihood of bad interaction with other applications, components, or class libraries.

Reference: "The JavaScript language essence" Douglas Crockford Zhao Zehin Shan Translation

Reprint please specify the source:

Jesselzj
Source: http://jesselzj.cnblogs.com

JavaScript language Essence Note 01

Related Article

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.