Variables and function declarations
Variable: A variable is a container for storing data (any data type) so that the script can access the variable by its name
stored data, if the variable is not assigned a value, the variable will save--undefined, for example: Var age, (also known as variable Declaration), and the variable can be divided into
Global variables and local variables.
function declaration: That is, one way to define a function, and the other is a function expression. The syntax for a function declaration is as follows:
Function name (parameter)
{function Body}
The most important feature of a function declaration is the promotion of a function declaration, which takes precedence over the function declaration before executing the code of the function body.
This allows the function declaration to be placed behind the called statement, for example:
Hello ();
function Hello () {
Alert ("Hello");
}
Scope
Scope: The execution environment in which variables exist, and scope controls the life cycle of variables and parameters. The execution environment defines a variable or function
Other data that you have access to, each execution environment has a variable object, and all variables and functions defined in the environment are stored in the object.
Each function has its own execution environment, which creates a scope chain for the variable object when executing the code.
A scope chain is essentially a list of pointers to variable objects, and he references but does not contain variable objects. Scope chain guarantees the right to execute functions
Access all the variables and functions of the ordered access, for example:
var rain = 1;
function Rainman () {
var man = 2;
function inner () {
var innervar = 4;
alert (rain);
}
Inner (); Call the inner function
}
Rainman (); Call the Rainman function
When querying for variable x, the three scope chain objects of this code are inner, Rainman, window
Inside the function body, local variables have a higher precedence than global variables of the same name, and the internal environment can access all external environments through the scope chain, but
The external environment cannot access any variables and functions in the internal environment, there is no block-level scope in JS (any set of statements in a pair of curly braces belongs to a
blocks, all variables defined in this block are inaccessible outside the code block, which we call block-level scopes.
This object
This object: the This object points to the object whose function is called by the method. This object depends on the letter
Number of execution environments, in JavaScript, variables and functions declared in the global scope are properties and methods of the Window object, so the function is called in the global execution environment, this
The object always points to the window, and if the function is invoked as a method of an object, this points to the object, or if it is called in the form of a constructor
This points to the newly constructed object. Take the Window object as an example:
var x = "Hello";
function SayHello () {
Alert ("This.x");
}
SayHello (); Hello
Window object
Window object: A Windows object that represents an instance of a browser opened in a browser, which is both a JavaScript
An interface that accesses the browser window is also the global object specified by ECMAScript. Variables and functions declared in the Global scope are window
object, the variables defined in the global scope differ from the properties defined directly on the window: global variables cannot pass
Delete operator. If the document contains a frame (frame or iframe label), the browser creates a window for the HTML document
Object, and an additional window object is created for each frame.
Ajax
Ajax: A Web-based development technique that creates interactive Web applications by exchanging small amounts of data in the background with the server,
Ajax makes it possible for Web pages to be updated asynchronously. This means that you can update a part of a webpage without reloading the entire page.
The core of Ajax technology is the XMLHttpRequest object (XHR), through the XMLHttpRequest object Ajax in the browser with the WEB server
Use asynchronous data transfer (HTTP request), and then insert the new information through the DOM into the page, so that the Web page is removed from the server
Request a small amount of information, rather than the entire page. But Ajax communication has nothing to do with data format, and the requested data is not necessarily XML data
The difference between asynchronous and synchronous
The difference between asynchronous and synchronous: synchronization: When Ajax sends a request, it continues to issue the next message while waiting for the server to return
Request execution of subsequent code
Async: When Ajax sends a request, the following code executes after waiting for the server side to return data
Objects and JSON
Json:json (JavaScript Object Notation) is a lightweight data interchange format that is based on ECMAScript's
A subset of completely language-independent text formats that make JSON an ideal data exchange language easy to read and write,
It is also easy for machine parsing and generation to transmit the same data, and JSON is smaller than XML.
The JSON syntax can represent three types of values: simple values, objects and arrays, simple values in JSON that represent strings, numeric values, Booleans, and
NULL, but does not support undefined; curly braces save objects, such as
{
"Name": "Mike",
"Age": 23
}//The properties of the object must be enclosed in double quotes, and the value of the property can also be a value of a complex type
Square brackets Save the array, and the JSON array takes the form of an array literal in JavaScript, for example:
[+, "Hello", true]
Arrays can also hold values for complex data types
The JSON object has two methods: Stringify () and Parse (), which serialize the JavaScript object to a JSON string, and the JSON
The string resolves to the native JavaScript value.
Cross-domain processing
Cross-domain processing: A cross-domain refers to a resource that requests another domain name from a Web page of one domain name. For example, from the http://www.baidu.com/page
To request http://www.google.com resources, as long as the protocol, domain name (including the primary domain name and sub-domain name), the port is any different, it is
As a cross-domain. Ajax communication via XHR, in general, the XHR object can only access resources that reside in the same domain as the page containing it.
But a reasonable implementation of cross-domain requests is also quite necessary.
CORS: Use a custom HTTP header for the browser to communicate with the server, for example: for simple get or post requests, the browser discovers this
A cross-origin Ajax request is a simple request that automatically adds an origin field to the header information.
JSONP:JSONP is a JSON that is called in a function, consisting of two parts, a callback function and a data: The callback function is when the response arrives
The function that should be called in the page, and the data is the JSON data that is passed into the callback function. JSONP is used by dynamic <script> elements
, you can specify a cross-domain URL for the src attribute when used
Closed Package
Closures: Closures refer to functions that have access to variables in another function scope, and generally nested functions produce closures such as:
function A () {
var i = 0;
Function B () {
Alert (i + +);
}
return b;
}
var C = A ();
C (); After executing var c=a (), the variable C actually points to function B, and then C () pops up a window showing the value of I (first 1).
This code actually creates a closure, because the variable C outside of function A refers to function B in function A, when function A's inner function B is the function a
A closure is created when a variable is referenced outside the The so-called "closure" is the definition of another function in the body of the constructor as the target
The method function of the object, which in turn references the temporary variable in the outer function body. When function A's inner function b is called by function a
A closure is created when a variable is referenced outside the
Closure: After the function is finished, the garbage collection mechanism of JavaScript does not reclaim the resources used by the function, because its intrinsic function
Executes a variable that needs to depend on the function, even though the scope chain of its execution environment is destroyed, but its active object is still stored in memory. (partial
The variable will be freed after the function has finished executing)
In the example if we execute C () for the second time; Will pop up with a value of 2,
Call () and apply ()
Call () and apply (): Functions in ECMAScript are objects, so functions also have properties and methods, and each function includes length
And the prototype property, the Length property represents the number of accepted arguments, and prototype saves all instance methods of the function.
Call () and apply () are the two non-inherited methods that each function contains, both of which are used to invoke a letter in a specific scope
Number, which is actually equal to the value of this object set in the function body. (For passing parameters)
Apply () Method: accepts two parameters, one is the scope in which the function is run, and the other is a parameter array (which can be an instance of array, or
Can be a arguments object).
Syntax: Apply (Thisobj,[argarray])
If Argarray is not a valid array or is not a arguments object, it will result in a TypeError.
If none of the Argarray and Thisobj parameters are provided, then the Global object will be used as a thisobj and cannot be passed any
What parameters.
Definition: A method of applying an object that replaces the current object with another object.
Call () method: He differs from the Apply () method only in the way that the parameter is received. For the call () method, the first parameter is the this value does not
The change is that the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be individually
Examples are raised.
Syntax: Call (Thisobj,object)
The call method can be used to invoke a method in place of another object. The call method changes the object context of a function from the initial context to
The new object specified by the thisobj. If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
Definition: Invokes one method of an object, replacing the current object with another object.
DOM Operations
DOM manipulation: The DOM (Document Object model) is an API (application programming Interface) for HTML and XML documents.
The DOM depicts a hierarchical tree of nodes that allows developers to add, remove, and modify portions of a page.
CreateElement (): Creates a new element node;
createTextNode (): Creates a new text node containing the given text
AppendChild (): Adds a new child node after the list of the last child nodes of the node is specified;
InsertBefore (): Inserts a given node in front of the given node of a given element node;
RemoveChild (): Removes a node from a given element;
ReplaceChild (): Replaces one node in a given parent element with another node;
CloneNode (): Creates an identical copy of the node that called the method;
getElementById ()/getelementsbytagname (): Gets a reference to a specific element or group of elements;
Write ()/writeln (): writes the input stream to the Web page;
GetAttribute (): Obtain the characteristics of the element;
SetAttribute (): Set element properties;
RemoveAttribute (): Completely remove the attributes of the element;
Normalize (): Merges adjacent text nodes into one node;
Splittext (): Divides a text node into two text nodes;
CreateAttribute (): Creates a new attribute for the element;
Prototype and prototype chain:
Prototypes: Each function we create has a prototype (prototype) attribute, which is a pointer to an object
This object contains properties and methods shared by a particular instance, so the prototype is the prototype of the object instance created by invoking the constructor
Object. Using a prototype object allows all object instances to share the properties and methods that it contains, such as:
function person () {
}
Person.prototype.name = "Mike";
Person.prototype.age = 29;
Person.prototype.sayName = function () {
alert (this.name);
};
var person1 = new Person ();
Person1.sayname (); "Mike."
var person2 = new Person ();
Person1.sayname (); "Mike."
The prototype property of the newly created function points to the prototype object of the function, and all the prototype objects automatically get a constructor property, which
The prototype property contains a pointer to the function where the property is located, for example: Person.prototype.constructor points to person,
In addition to the constructor property, the prototype object contains the name age property that was added later, two instances of the person constructor
It is through the prototype object that it is shared to its properties and methods.
Although the values saved in the prototype can be accessed through an object instance, the values in the prototype cannot be overridden through an object instance
Prototype chain: The basic idea of a prototype chain is to implement inheritance in ECMAScript, which is to have one reference type inherit another reference
The properties and methods of the type. Each constructor has a prototype object, and the prototype object contains a pointer to the constructor, and the instance packages
Contains an internal pointer to a prototype object that, if a prototype object equals an instance of another object, will contain a prototype object that refers to the
A pointer to another prototype, while another prototype contains a pointer to another constructor, which, in so doing, forms the instance and prototype
Chain, which is the prototype chain.
When an instance property is accessed, the attribute is first searched in the instance, and if the attribute is not found, then the prototype chain is searched step-by-step
Event handling
Event handling: The interaction between JS and HTML is accomplished through events, which are specific moments of interaction that occur in a document or browser window.
Event Flow: Event Flow describes the order in which events are received from the page
Event bubbling: Is received by the most specific element and then propagated up to a more advanced node, that is, events propagate up the DOM tree until the document
Object.
Event capture: Nodes that are not specific should receive events earlier, which is equivalent to propagating down the DOM node tree to the actual target of the event,
Event is captured from the Window object, starting with the
Event handlers: Functions that affect an event are called event handlers (or event listeners) such as: The event handler for the Click event is
OnClick
Load: When the page is fully loaded (including external resources such as all images, JS files, CSS files, etc.), the Load event above the window will be triggered;
Unload Event: This event is triggered when the document is completely uninstalled, or the user switches from one page to another;
Resize event: Triggered when the browser window is resized to a new height or width;
Scroll event: The scroll event occurs on a Window object, but it actually represents the change of the corresponding element in the page;
Blur: Triggered when the element loses focus, this event does not bubble, and all browsers support it;
Domfocusin: Triggered when the element receives focus, is equivalent to the HTML event focus, but it will bubble, only opera supports;
Domfocusout: Triggered when the element loses focus, is equivalent to the HTML event blur, but it will bubble, only opera support;
Focus: Triggers when the element gets focus, does not bubble all browsers support it;
Focusin: Triggered when the element receives focus, is equivalent to the HTML event focus, but it bubbles;
Focusout: Triggered when the element loses focus, this event is a generic version of the HTML event blur;
Click: triggers when the mouse is clicked or the ENTER key is pressed;
DblClick: Triggered when the mouse is double-clicked;
MouseDown: When the user presses any mouse button, the trigger cannot be triggered by the keyboard;
MouseEnter: triggered when the mouse cursor is first moved from outside the element to the range of elements, the event does not bubble and is moved to the descendant element.
does not trigger;
MouseLeave: Fires when the mouse cursor above the element is moved outside the range of elements, the event does not bubble, and is moved to the descendant element.
does not trigger;
MouseMove: When the mouse pointer moves inside the element, it is repeatedly triggered;
Mouseout: Triggered when the mouse pointer is over an element and then the user moves it into another element;
MouseOver: Triggered when the mouse pointer is outside an element and the user first moves it within the bounds of another element;
MOUSEUOP: Triggers when the user releases the mouse;
KeyDown: Triggered when the user presses any key on the keyboard, if pressed, the event is repeatedly triggered;
KeyPress: Triggered when the user presses a character key on the keyboard, and the event is triggered repeatedly if pressed or not (ESC is also triggered);
KeyUp: Triggered when the user releases the key on the keyboard;
Array method
Array methods: Arrays are also variables, but arrays can store multiple values, which is an ordered list of stored data, but ECMAScript
Each item in the array can hold a value of any data type.
Properties of the Array object:
Length: Sets or returns the number of elements in the array
Constructor: Returns a reference to the array function that created this object
Prototype: Adding properties and methods to an object
Array method:
Concat (): Used to concatenate two or more arrays, the method does not alter an existing array, but only returns a copy of the connected array;
var a = [n/a];
document.write (A.concat (4,5)); 1,2,3,4,5
Join (): Used to put all the elements in the array into a string, and the elements are delimited by the specified delimiter.
var a = [n/a];
document.write (A.join ("|")); 1|2|3
Pop (): Used to delete and return the last element of an array
var a = [n/a];
document.write (A.pop ()); 3
Push (): Adds one or more elements to the end of the array and returns the new length
var a = [n/a];
document.write (A.push ("4", "5")); 5
Reverse (): Reverses the order of the elements in the array, changes the original array, and does not create a new array
var a = [n/a];
document.write (A.reverse ()); 3,2,1
Shift (): Removes the first element from the array and returns the value of the first element
Slice (): Returns the selected element from an existing array, Arrayobject.slice (Start,end) The method does not modify the array, but returns a sub-array
var arr = new Array (6)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
ARR[3] = "James"
ARR[4] = "Adrew"
ARR[5] = "Martin"
document.write (Arr.slice (2,4))//thomas,james
document.write (arr)//george,john,thomas,james,adrew,martin
Sort (): Sorts the elements of an array, sorted in the order of character encodings
Splice (): Add/Remove elements to/from the array and return the deleted element
var arr = new Array (6)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
ARR[3] = "James"
ARR[4] = "Adrew"
ARR[5] = "Martin"
Arr.splice (2,0, "William")
document.write (arr)//george,john,william,thomas,james,adrew,martin
Tosource (): Represents the source code of the object that is inherited by all objects derived from the Array object
ToString (): Converts the array to a string and returns the result
toLocaleString (): Converts an array to a local string
Unshift (): Adds one or more elements to the beginning of the array and returns the new length
var arr = new Array ()
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
document.write (Arr.unshift ("William"))//4
document.write (arr)//william,george,john,thomas
ValueOf (): Returns the original value of the array object, which is inherited by all objects derived from the array object
Regular expressions
Regular expressions: In general, the most important function of regular expressions is to match characters. JavaScript uses the RegExp type to
Supports regular expressions, using Perl syntax to create a regular expression: var re =/pattern/flags; Where the pattern part is to
Matching characters, flags (flags) to indicate the behavior of the regular expression, G, I, M, respectively, representing the global match, ignoring case, multi-line modulo
, three properties can be freely combined to co-exist.
All meta characters used in the pattern must be escaped with the escape character "\", including: ( [ { \ ^ $ | ) ? * + .
Another way to create a regular expression is to use the RegExp constructor, which receives two parameters: the string pattern to match and an optional
The flag string, for example: var re = new RegExp ("Bat", "G"), the metacharacters under this method need to be escaped with a "//" double escape character.
Unlike regular expressions created using regular expression literals and regexp constructors, regular expression literals will always share the same
RegExp instance, and each new RegExp instance created with the constructor is a new instance
RegExp Instance Properties
Global: is the starting position for the first match of the current expression pattern, counting from 0 onwards. Its initial value is-1, and the Index property changes each time a successful match is made.
IgnoreCase: Returns the state of the IGNORECASE flag (i) that was specified when the RegExp object instance was created. If the I flag is set when the RegExp object instance is created, the property returns True, otherwise false and the default value is False.
LastIndex: Is the next position of the last character in the first match of the current expression pattern, counting from 0, often as the starting position to continue the search, with an initial value of-1, indicating that the search starts from the starting position, and the value of the LastIndex property changes each time a successful match is made. (Only use the EXEC () or test () method to fill in, otherwise 0)
MultiLine: Returns the state of the MultiLine flag (m) that was specified when the RegExp object instance was created. If the M flag is set when the RegExp object instance is created, the property returns True, otherwise false and the default value is False.
Source: Returns the expression text string specified when the RegExp object instance was created
Search () Method: Used to find the first occurrence of a substring in the original index, no return 1
"Abchello". Search (/hello/); 3
Replace (): The method is used to replace the substring "Abchello" in the string. Replace (/hello/, "hi"); "Abchi"
Test () Method: for testing whether a string contains substrings, returns a Boolean value
/hello/.test ("Abchello"); True
Match (): Used to capture substrings in a string into an array. By default, only one result is captured in the array, regular expressions
When you have a "Global capture" attribute (add parameter g when defining a regular expression), all results are captured in the array
"ABCHELLOASDASDHELLOASD". Match (/hello/g); ["Hello", "Hello"]
EXEC (): This method also captures the string from the string that satisfies the condition into the array, and the Exec () method can only capture the first match at a time
Substring into an array, regardless of whether the regular expression has global properties
.: [^\n\r]//any character except line break and carriage return
\D:[0-9]//numeric characters
\D:[^0-9]//non-numeric characters
\s:[\t\n\x0b\f\r]//blank character
\s:[^ \t\n\x0b\f\r]//non-whitespace characters
\W:[A-ZA-Z_0-9]//Word character (all letters)
\W:[^A-ZA-Z_0-9]//non-word characters
?: appears 0 or one time
*: appears 0 or more times (any time)
+: Occurs one or more times (one time to the Tao)
{n}: corresponds to 0 or n times
{n,m}: appears at least n times but not more than m times
{N,}: appears at least n times
^: Opening
$: End
\b: Word boundaries, meaning characters other than [a-za-z_0-9]
\b: Non-word boundary
JavaScript Basics Summary