A blog post giving a full view of JavaScript

Source: Internet
Author: User
Tags argumentlist javascript array hasownproperty
This article introduces the JavaScript language to professional programmers. It is a small language.

This article introduces the JavaScript language to professional programmers. It is a small language. If you are familiar with other programming languages, 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't this a string? Yes!"'A' // The character A"" // An empty string

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

var s = "Hello World!";s.length == 12

You can add a function to these simple types. You can add an int () function to all numeric types. When you call Math.PI.int (), 3 is returned.

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 ).

var myHashtable = {};

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

var myHashtable = new Object();

The results are indeed the same.

The for statement can be used to enumerate objects.

for (var n in myHashtable) {    if (myHashtable.hasOwnProperty(n)) {        document.writeln("

" + n + ": " + myHashtable[n] + "

"); }}

The result should be

name: Carl Hollywood

city: Anytown

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, but can appear as strings. The value can be any type of text or expression.

var myObject = {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 an object and an array is the length attribute. The length attribute is always 1 larger than the maximum integer key. There are two ways to create a new array.

var myArray = [];var myArray = new Array();

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, 30, 31];slides = [    {url: 'slide0001.html', title: 'Looking 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 uses function declaration instead of 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 undefined, this 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:

function sum() {  // Take any number of parameters and return the sum    var total = 0;    for (var i = 0; i < arguments.length; ++i) {        total += arguments[i];    }    return total;}

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.

function name(argumentlist) block

Functions can be nested and must be closed. There are 0 or more parameter names separated by commas.BlockIs attached by 0 or more.

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

var name = function name (argumentlist) block ;
Function operator

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

function name(argumentlist) block

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 expression foo. bar (), this variable points to the object foo, which serves as an additional parameter of the function bar. Function bar can use this to enter the object to find useful projects.

A deeper representation of do. re. mi. fa (), this variable points to the object do. re. mi, rather than the object do. In a simple function call, this points to a Global Object (also called window) that is not too big ). When calling an internal function, the correct action is to protect the current value of this.

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 is called with the new prefix:

new Constructor(parameters...)

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

The new prefix changes the meaning of this. It is 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 the return statement is explicitly used for replacement.

The constructed object will contain a secret prototype link field pointing to the prototype member of the constructor.

Prototype)

The object contains a hidden connection property. This link points to prototype, which is 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, undefined is returned.

Prototype is used to link a series of Inheritance

Members can be added to prototype by allocation. This defines a class Demo, which inherits from Ancestor and adds its unique method foo.

function Demo() {}Demo.prototype = new Ancestor();Demo.prototype.foo = function () {};
Variable

Use the var statement to define variables. When a variable is defined inside a function, var hasFunction-scope)Level. This variable cannot be accessed outside the function. JavaScript has no other range domain granularity. More specifically, JavaScript does notBlock-scope).

Any variables used in the function but not explicitly defined by var will be assumed to be global objects.

Any variable not explicitly initialized will be assigned to undefined.

A variable is not strongly typed. A variable references an object, String, number, Boolean value, null value, or undefined.

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

JavaScript does not have the void type, so each function must return a value. The default value is undefined except the constructor. The default return value of the constructor is this.

Statement

Statements include var, if, switch, for, while, do, break, continue, return, try, throw, and with. Most of the statements are the same as those in C.

A var statement is a list of one or more variable names separated by commas (,) with optional initialization expressions.

var a, b = window.document.body;

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

In the if, while, do, and logical operators, JavaScript is treated as false, null, undefined, "" (null String ), and the number 0 as false ). All other values are considered true ).

The case mark in the switch statement can be an expression, which does not have to be a constant or a string.

There are two forms of for statements, the first one is like this(Init; Test; Inc)Format. The second is the object repeat.

for (name in object) {    if (object.hasOwnProperty(name)) {        value = object[name];    }}

The order in which names are generated for each name in the object is uncertain.

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

With statement 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.

+ The operator is used for addition and String concatenation. If any operand is a string, concatenation may cause an error. For example, '$' + 3 + 4 will get '$34 ', instead of '$7 '.

+ Character operands can be converted into numbers as a prefix operator.

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

& Operator, generally called "logic and "(Logical and), Which is also calledGuardIf the first operand is false, null, undefined, "" (null String), or number 0, the first operand is returned. Otherwise, the second operand is returned. This provides a convenient way to test the null value:

value = v || 10; /* Use the value of v, but if vdoesn't have a value, use 10 instead. */

| The operator is generally called "logic or "(Logical or), Which is also calledDefaultIf the first operand is false, null, undefined, "" (null String), or number 0, the second operand is returned. Otherwise, the first operand is returned. This provides a convenient way to set default values:

value = v || 10; /* Use the value of v, but if vdoesn'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, void is a prefix operator rather than a type. It always returns the undefined value. 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.

The typeof operator returns 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, this points to it, but in most cases it is not. In the browser, window and self are global object members pointing to the 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:

abstractboolean break bytecase catch char class const continuedebugger default delete do doubleelse enum export extendsfalse final finally float for functiongotoif implements import in instanceof int interfacelongnative new nullpackage private protected publicreturnshort static super switch synchronizedthis throw throws transient true try typeofvar volatile voidwhile 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. As a var
  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.

This article is available at http://www.nowamagic.net/librarys/veda/detail/603.

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.