Overview of JavaScript language (not exclusive)

Source: Internet
Author: User
Tags argumentlist javascript array hasownproperty
ArticleDirectory
    • Object
    • Array
    • Define functions
    • Global Object
    • Insert time of semicolon
    • Reserved Words

Reprinted: http://svza.blogspot.com/2007/03/javascript_09.html here format may look good (this seems to have. Flip. Wall .)

By the way: http://dancewithnet.com/snapshot/code-conventions-for-the-javascript-programming-language/

Introduction

This article is professionalProgramIt is a small language, if you are familiar with otherProgramming LanguageSo this article is not that hard to understand.

Javascript is not Java. They are two completely different languages. Javascript is not a subset of Java. Javascript cannot be considered Java (Java is Java ). Javascript shares the C language syntax like Java, but Javascript is more similar to scheme and self from a deeper perspective. It is a small language, but it is indeed powerful and rich. You should take a good look at it and you will find that it is not a toy language, but a complete language with many distinctive features.

Javascript is a formal language that does not take too much time to learn. It is better suited to some tasks, for example, it is more suitable for client programming than Java. With my practical experience, I found that working with JavaScript makes me a better Java programmer because it brings me a rich set of skills.

When I first came into contact with JavaScript, I thought it was not worth my attention. Later, I was amazed at it because I found that it is such an effective programming language hidden in the browser. I first noticed it in Javascript's initial statement at Sun and Netscape. They made a lot of false statements on JavaScript to prevent it from competing with Java. These misstatements continue to fill these bad JavaScript books that are provided only for dummies and amateurs.

History

Javascript is developed by Brendan eich of Netscape as a Page scripting language in navigator 2. It is a very expressive dynamic programming language, because of the relationship with the browser, it immediately becomes red and red. It never gets a problem that can be corrected for it and a test cycle based on the real purpose of use, which all results in it being powerful but flawed.

This article describes ecmascript Version 3 (also called JavaScript 1.5 ). Microsoft and Netscape have developed a version with no defects corrected. The new version of the language may not be called JavaScript and is not discussed in this article.

Data Type

Javascript contains a small set of data types, which have three simple types:Boolean,Number, AndString; Special values:Null,Undefined; All others are based onObjectType Change.

The boolean type has two values:TrueAndFalse.

A number is a 64-bit floating point value, similar to a Java double. It does not have an integer. Division operations may result in decimal places. Numbers include special valuesNan(Not a number) andInfinity.

A string is composed of zero to multiple Unicode characters. There is no separate byte type. A byte is depicted as a string with a length of 1. String is'Symbol or"The single quotation marks and double quotation marks can be replaced, but must be matched before and after.

 
'This is a string .'
 
"Isn' tThisA string? Yes! "
 
'A' // The character
 
"" // An empty string

Escape\Character, Just Like java. The string is unchangeable. The string hasLengthAttribute Class to view the number of characters used by the string.

 
VaRS ="Hello world! "; S. Length = 12

You can add functions for these simple types. You can addINT ()When you callMath.pi.int ()The result is 3.

An implementation may provide other types, such as the date (dates) type and regular expression type, but their actual types are the object type, and all other types are the object type.

Object

Javascript has very nice symbolic convenience to deal with those key-Value Sets (hash tables) (HashTables ).

 
VaRMyhashtable = {};

This statement declares a set of key values and assigns them to a local variable. Javascript is of a weak type, so we cannot declare it with the type name. We use indexes to add, replace, and obtain objects from key-value combinations.

 
Myhashtable ["Name"] ="Carl Hollywood";

You can also use the "." method to bring a little convenience.

 
Myhashtable. City ="Anytown";

When an index is a valid reserved word, the dot symbol becomes useless. This is because of a language definition error. Reserved Words cannot be used for Dot symbols, but can be used for indexing.

You will find that the Javascript hash table symbol is very similar to the Java object and array symbol. Javascript makes this more complex: objects and hash tables are the same thing, so I can write

 
VaRMyhashtable =NewObject ();

The results are indeed the same.

UseForThe statement can be used to enumerate objects.

For(VaRNInMyhashtable ){If(Myhashtable. hasownproperty (N) {document. writeln ("<P>"+ N +":"+ Myhashtable [N] +"</P>");}}

The result should be

 
<P> name: Carl Hollywood </P> <p> City: anytown </P>

An object is a set of key/value pairs. A key is a string (or other elements such as numbers converted into strings), and a value can be of any data type, including other objects. Objects are often implemented as hash tables, but no hash tables (such as hash functions or rewrite functions) are visible by nature.

Objects are easily nested into other objects, and object expressions can be used in content objects.

 
This. DIV = Document. Body. Children [document. Body. Children. Length-1];

In the text expression of an object, an object describes a group of key/value pairs that are separated by commas. The key can be a colon identifier or string after it. Due to a language definition error, the system reserved words cannot appear as identifiers,However, it can appear in string mode.. The value can be any type of text or expression.

VaRMyobject = {Name:"Jack B. Nimble",'Goto':'Jail', Grade:'A', Level: 3 };
 
Return{Event: event, OP: event. type, to: event. srcelement, X: event. clientx + document. body. scrollleft, Y: event. clienty + document. body. scrolltop };
 
Emptyobject = {};

The Object Mode of JavaScript is the basis of the JSON data exchange format.

New members can be attached to any object at any time.

 
Myobject. Nickname ='Jackie the bee';

Arrays and functions are implemented as objects.

Array

Arrays in JavaScript are also hash table objects, which are well matched with rare array programs. When you declare an array, you do not need to declare its size. The array will grow itself, which is like a Java vector (vectors ). The array value is located based on the key rather than the offset, which makes the Javascript array very convenient, but not suitable for those numeric analysis applications.

The main difference between objects and arrays is thatLengthAttribute.LengthThe property is always 1 greater than the maximum integer key. There are two ways to create a new array.

 
VaRMyarray = [];VaRMyarray =NewArray ();

An array is not a strong type. It can contain numbers, strings, Boolean values, objects, functions, and arrays. You can mix strings, numbers, and objects in an array. You use arrays as nested sequences, which is similar to S-expressions. The first index of the array is usually 0.

When an array is added with a new element, its index is longer than the array length. Then the length of the array is changed to adding 1 to the index. This convenient feature makes it easy for arrays to increase the number of elements in the for loop.

The array has a symbol mark similar to the object.

Mylist = ['Oats','Peas','Beans','Barley']; Emptyarray = []; month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31]; slides = [{URL:'Slide0001.html', Title:'Looking & nbsp; ahead'}, {URL:'Slide0008.html', Title:'Forecast'}, {URL:'Slide0021.html', Title:'Summary'}];

The new element is added to the array as an allocation.

 
A [I + J] = f (a [I], a [J]);
Function

JavaScript Functions look like C functions, but JavaScript usesFunctionDeclaration rather than type keywords. When a function is called, passing a specified number of parameters is not mandatory. Excessive parameters are ignored, and the missing parameters are assigned a valueUndefinedThis makes it easy to write a function that processes optional parameters.

A function has the right to use a parameter array that contains all actually called parameters. This makes it easy to process a parameter with a variable, for example:

FunctionSum (){// Take any number of parameters andReturnThe sumVaRTotal = 0;For(VaRI = 0; I <arguments. length; ++ I) {total + = arguments [I];}ReturnTotal ;}

Javascript has internal functions, which play the same role as Java's internal classes, but not so obvious. Javascript also has anonymous functions that act as lambda expressions. Functions have lexical scopes.

Function is the first lesson of an object. This means that a function can be stored in an object and passed as a parameter to other functions.

Define functions

There are three ways to define a function: function declaration, function operator, and function constructor.

Function Declaration

Function Declaration creates a named function in the current scope.

FunctionName(ArgumentlistBlock

Functions can be nested and must be closed. There are 0 or more parameter names separated by commas.BlockIs composed of 0 or more{}Attached.

The function declaration is stenographer in the form of a function operator:

VaRName= FunctionName(Argumentlist)Block;

Function operator

The function operator is a prefix operator that generates an object. It looks similar to the function declaration.

FunctionName(ArgumentlistBlock

The name is optional. If the name is provided, it can be used for recursive function calls. This is also used to access function object members (except IE ). If the name is omitted, it is an anonymous function.

Function operators are often used to allocate them to a prototype ).

Function operators are often used to define a function in a proper place, which is faster than getting a callback when writing. (The function operator can also be used to define functions in-place, which is handy when writing Callbacks .)

Function Constructor

The function constructor carries characters in parameters and internally to generate a function object.

New Function (Strings...)

Do not use this method. Due to the convention of language reference, it is difficult to properly express a function body as a string. In character form, early error checks do not work. This is also very slow, because the compiler must be triggered whenever the constructor is called, and this wastes memory, because each function requires its own implementation.

Object and This

A function is an object that can contain members, just like other objects. This allows a function to contain its own data table, which also allows an object to act as a "class", including constructors and a set of related functions.

A method can be a member of an object. When a function is a member of an object, it becomes a "method ". There is a special variable called "this". When an object is called, it points to the object.

For example, in the expressionFoo. Bar ()Medium,ThisThe variable points to the object.FooAs a functionBar. FunctionBarAvailableThisEnter the object to find a useful project.

A deeper RepresentationDo. Re. Mi. FA (),ThisThe variable points to the object.Do. Re. MiInstead of ObjectsDo. In a simple function call,ThisPoint to a global object (also calledWindow). When calling an internal function, the correct action is to protect the currentThis.

Constructor

When a function is used to initialize an object, it is calledConstructorThe order of calling a constructor is slightly different from that of calling a common function. A constructor carriesNewPrefix called:

NewConstructor(Parameters...)

According to the habit, the first letter of the constructor name is capitalized.

NewThe prefix has changed.ThisIs not a common value, but a new object ". The body of the constructor initializes the members of the object. After construction, a new object will be returned, unless explicitly usedReturnStatement.

The constructed object will contain a secret pointing to the constructorPrototype.

Prototype)

The object contains a hidden connection property. The link pointsPrototypeIs the constructor instance.

When an entry is accessed from an object in the form of a vertex or index, if the entry is not found in the object, check its link object. If it is not found in the Link object, if the link object itself has a link object, check the link object. If all links of the link object are checked, the system returnsUndefined.

Prototype is used to link a series of Inheritance

Members can be addedPrototypeHere, we define a classDemo, It starts fromAncestorInheritance, and added its unique methodFoo.

 
FunctionDemo () {} demo. Prototype =NewAncestor (); demo. Prototype. Foo =Function(){};
Variable

Define variable usageVaRStatement. When a variable is defined inside a function,VaRYesFunction-Scope)Level. This variable cannot be accessed outside the function. Javascript has no other range domain granularity. More specifically, JavaScript does notBlock-Scope).

Any function that is used but not usedVaRVariables that are clearly defined are assumed to be global objects.

Any variable not explicitly initialized will be assignedUndefined.

Variables are not strongly typed. A variable references an object, String, number, Boolean value,NullValue orUndefined.

When a function is called, a new set of variables are generated, which allows recursive calls.

Close

Functions can be defined in other functions. Internal functions have the right to use variables defined by external functions. If an internal function is referenced (for example, a callback function ), then the variables of the external function will continue to exist.

Return Value

No JavascriptVoidType, so each function must return a value. The default value isUndefinedThe default return value of the constructor isThis

Statement

Statements includeVaR,If,Switch,For,While,Do,Break,Continue,Return,Try,Throw, AndWithMost of them are the same as those in C.

VaRA statement is a list of one or more variable names separated by commas with optional initialization expressions.

 
VaRA, B = your own Doc ument. Body;

IfVaRIf the statement appears outside all functions, a global variable is declared. If it appears in a function, a local variable is declared.

InIfStatement,WhileStatement,DoIn the statements and operators that conform to the logic, JavaScript is consideredFalse,Null,Undefined,""(Null String), and number0False ). All other values are considered true ).

InSwitchStatementCaseTags can be expressions. They do not have to be constants or strings.

There are two formsForStatement, the first type is like this(Init; Test; INC)Format. The second is the object repeat.

 
For(NameInObject ){If(Object. hasownproperty (name) {value = object [name] ;}}

RunObjectEveryNameThe order in which names are generated is uncertain.

A statement can have a prefix, that is, an identifier followed by a colon.

WithStatement should not be used

Operator

Javascript has complete operators. Most of them work in the same way as C language, but note some minor differences.

+Operators are used to add and concatenate strings. If any operand is a string, concatenation may cause errors, such'$' + 3 + 4Will get'$34'Instead'$7'.

+It can be used as a prefix operator to convert character operands into numbers.

!!It can be used as a prefix operator to convert the operand to a Boolean value.

&&Operators, generally referred to as "logic and "(Logical and), Which is also calledGuardIf the first operand isFalse,Null,Undefined,""(Null String) or number0The first operand is returned. Otherwise, the second operand is returned. This provides a convenient testNullValue Method:

 
VaRValue = P & P. Name;/* The name value willonly be retrieved from PIfP has a value, avoiding an error. */

|Operators are generally referred to as "logical or "(Logical or), Which is also calledDefaultIf the first operand isFalse,Null,Undefined,""(Null String) or number0Otherwise, the first operand is returned. This provides a convenient way to set default values:

 
Value = v | 10;/* Use the value of V,IfVdoesn' t have a value, use 10 instead. */

Javascript supports a set of bitwise AND shift operators, but it does not even provide an integer to apply them. When a numeric operand (a 64-bit floating point number) is converted to a 32-bit integer before the operation, and then converted back to the floating point number, what will happen after the operation?

In JavaScript,VoidIs a prefix operator rather than a type, it always returnsUndefinedValue. This is just a little bit of value. The reason I mentioned it is that in case you accidentally get used to it, it won't be confused by its weird behavior.

TypeofReturns a string based on its operands.

Error generated.

Object 'Object'
Array 'Object'
Function 'Function'
String 'String'
Number 'Number'
Boolean 'Boolean'
Null 'Object'
Undefined 'Undefined'
Global Object

The global object contains all the functions and all the variables and objects not defined in any function. Surprisingly, the global variable does not have a definite name in the language. Sometimes,ThisPoint to it, but in most cases it is not. In the browserWindowAndSelfIt is a global object member pointing to a global object. Therefore, an indirect addressing method is provided.

If a variable can be accessed but not found in the current domain, it will be searched in the global object range. If not, an error will be returned.

The ecmascript specification does not discuss the feasibility of multiple global objects, orContextBut the browser supports this. Each window has its own global object.

Insert time of semicolon

An error in this language is inserted with a semicolon in a timely manner. One trick is to use a semicolon to terminate the statement. It is reasonable to use various development tools for insertion. There is no need to let the compiler do it for the sake of language definition. Use a semicolon.

Reserved Words

Javascript's support for reserved words in the system is severely overhead. These reserved words are:

Abstract
Boolean Break Byte
Case Catch Char class const Continue
Debugger Default Delete Do Double
Else Enum export extends
False Final Finally FloatFor 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

A large part of these keywords are not used in Javascript. A reserved word cannot be used in the following method:

    1. Mark as an object name
    2. Members in point form
    3. As a function parameter
    4. AsVaR
    5. As an absolute global variable
    6. As a statement label)

The first two restrictions are unforgivable and never used. The following two applications are acceptable, but they are very unreliable.

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.