(Updated continuously…)
Chapter 4 – Variables, scopes, and Memory
The target
- Use raw and reference values through variables
- Understand the execution Context
- Understand garbage collection
Original and reference values
- Original values: Undefined, Null, Boolean, Number, String, and Symbol. According to the value (by
Value) access.
// Let name = "Nicholas"; name.age = 27; console.log(name.age); // undefinedCopy the code
- Reference values: Access by reference. A reference value can be added, modified, and deleted at any time.
- Duplicate values
When the original value is assigned to another variable, the original value is copied to the location of the new variable. When a reference value is assigned to another variable, the copied value is actually a pointer to an object stored in heap memory.
- Passing parameters
Arguments to a function are passed by value, which is equivalent to copying
Function addTen(num) {num += 10; return num; } let count = 20; 86 第 4 页 Let result = addTen(count); console.log(count); // 20, no change console.log(result); / / 30Copy the code
Function setName(obj) {obj.name = "Nicholas"; } let person = new Object(); setName(person); console.log(person.name); // "Nicholas"Copy the code
Execution context and scope
Each context has an associated variable object on which all variables and functions defined in that context reside. Although the variable object cannot be accessed through code, it is used for data processing in the background. The context is destroyed after all of its code has been executed, including all variables and functions defined on it. Each function call has its own context. When code execution flows into a function, the context of the function is pushed onto a context stack. After the function completes execution, the context stack pops the function context, returning control to the previous execution context. When the code in the context executes, it creates a scope chain of variable objects. This chain of scopes determines the order in which the code at each level of context accesses variables and functions. The variable object of the context in which the code is executing is always at the front of the scope chain. If the context is a function, its activation object is used as a variable object. Active objects initially have only one definition variable: arguments. (This variable is not available in the global context.) The next variable object in the scope chain comes from the containing context, and the next object comes from the next containing context. And so on up to the global context; The variable object of the global context is always the last variable object in the scope chain.
-
Global context
-
In browsers, the global context is what we call the Window object
The garbage collection
-
The basic idea: Determine which variable will no longer be used, and then release the memory it occupies.
-
Tag strategy: tag cleanup and reference counting.
-
Tag cleanup (common) : When a variable is introduced into the context, such as declaring a variable inside a function, the variable is tagged with a tag that exists in the context. Variables are also marked out of context when they are out of context.
-
Reference counting: Counts the number of times each value is referenced. When you declare a variable and assign it a reference value, the number of references to that value is 1. If the same value is assigned to another variable, the number of references is increased by one. Similarly, if the variable holding a reference to that value is overwritten by another value, the number of references is reduced by one. When a value has zero references, the next time the garbage collector runs, it frees memory for the zero reference value.
-
Performance garbage collectors run periodically, and if many variables are allocated in memory, performance can suffer, so scheduling garbage collectors is important.
-
Hide classes and delete operations
At run time, V8 associates the created objects with hidden classes to track their attribute characteristics. Objects that can share the same hidden class perform better
Function Article() {this.title = 'Ceremony Features Kazoo Band'; // function Article() {this.title =' Ceremony Features Kazoo Band'; } let a1 = new Article(); let a2 = new Article(); a2.author = 'Jake';Copy the code
Function Article(opt_author) {this.title = 'Ceremony Features Kazoo Band'; function Article(opt_author) {this.title =' Ceremony Features Kazoo Band'; this.author = opt_author; } let a1 = new Article(); let a2 = new Article('Jake');Copy the code
Dynamically deleting attributes has the same consequences as dynamically adding attributes.
// low function Article() { this.title = 'Inauguration Ceremony Features Kazoo Band'; this.author = 'Jake'; } let a1 = new Article(); let a2 = new Article(); delete a1.author; Copy the code
function Article() { this.title = 'Inauguration Ceremony Features Kazoo Band'; this.author = 'Jake'; } let a1 = new Article(); let a2 = new Article(); a1.author = null; Copy the code
-
A memory leak
- Accidentally declare global variables
function setName() { name = 'Jake'; } Copy the code
- The timer
let name = 'Jake'; setInterval(() => { console.log(name); }, 100); Copy the code
- Use JavaScript closures
let outer = function() { let name = 'Jake'; return function() { return name; }; }; Copy the code
-
Static allocation with object pooling
Chapter 13 – Client Detection
The target
- Usability test
- History of user agent detection
- Software and hardware inspection
- Testing strategies
Ability to detect
Capability detection (also known as feature detection) is a simple set of detection logic used in JavaScript runtime to test whether the browser supports a certain feature.
/ / the if (object. PropertyInQuestion) {/ / using object. PropertyInQuestion}Copy the code
Safety capability testing
Function isSortable(object) {return typeof object.sort == "function"; }Copy the code
Browser analysis based on capability detection
// Check whether the browser supports Netscape plugin let hasNSPlugins =!! (navigator.plugins && navigator.plugins.length); // Let hasDOM1 =!! (document.getElementById && document.createElement && document.getElementsByTagName);Copy the code
It is not always possible to determine which browser is being used by detecting one or a group of capabilities. Capability checks are best used to decide what to do next, not necessarily as a marker for identifying browsers.
User agent detection
User agent detection determines what browser is being used from the user agent string of the browser. The userAgent string is included in the header of each HTTP request and is accessible in JavaScript through navigator.useragent.
navigator.userAgent
Copy the code
Identify the browser and operating system
- Identify browser developer information
navigator.vendor
// "Google Inc."
Copy the code
- Identify the operating system on which the browser is running
navigator.platform
// "MacIntel"
Copy the code
- Screen.colordepth and screen.pixelDepth return the bit depth of the color per pixel of the display
console.log(screen.colorDepth); // 24 console.log(screen.pixelDepth); / / 24Copy the code
- The Geolocation API exposes the geographical location of the current device.
navigator.geolocation
// Geolocation {}
Copy the code
- Connection properties
navigator.connection
Copy the code
- Obtaining battery Information
There are four events that monitor battery information changes
- Onchargingchange // When charging status changes
- Onchargingtimechange // When chargingtime changes
- Ondischargingtimechange // Add discharge time changes
- Onlevelchange // When the percentage of charge changes
navigator.getBattery().then((b) => console.log(b));
Copy the code
- Processor core number
navigator.hardwareConcurrency
// 8
Copy the code
- Device memory size (0.5 for 512MB and 4 for 4GB)
navigator.deviceMemory
// 8
Copy the code
- Maximum contact point
The computer without a touch screen is 0
navigator.maxTouchPoints
// 0
Copy the code
Chapter 17 – Events
The target
- Understand the flow of events
- Use event handlers
- Understand the different types of events
Flow of events
-
The event flow describes the order in which the page receives events.
-
Event bubbling: Fires from the most specific element (the deepest node in the document tree) and propagates up to less specific elements (the document)
- Event capture: Event capture means that the least specific node should receive the event first, and the most specific node should receive the event last.
- Event bubbling is generally recommended, but event capture can be used in special cases.
The DOM event flow
Event capture, reach target, and event bubbling.
Event handler
- Start with “on” : onclick
- In the HTML
<input type="button" value="Click Me" onclick="console.log('Clicked')"/>
Copy the code
- DOM0
let btn = document.getElementById("myBtn");
btn.onclick = function() {
console.log("Clicked");
};
Copy the code
- In the DOM2
let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
console.log(this.id);
}, false);
Copy the code
- IE
var btn = document.getElementById("myBtn");
btn.attachEvent("onclick", function() {
console.log("Clicked");
});
Copy the code
- Cross-browser event handlers
Var EventUtil = {addHandler: function(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; }}};Copy the code
// Use EventUtil let BTN = document.getelementById ("myBtn") let handler = function() {console.log("Clicked"); }; EventUtil.addHandler(btn, "click", handler); Eventutil.removehandler (BTN, "click", handler);Copy the code
The event object
Properties/methods | The class type | Read/write | Said Ming |
---|---|---|---|
bubbles | Boolean value | read-only | Indicates whether the event bubbles |
cancelable | Boolean value | read-only | Indicates whether the default behavior of an event can be undone |
currentTarget | The element | read-only | The element of the current event handler |
defaultPrevented | Boolean value | read-only | True: preventDefault() has been called (new in DOM3Events) |
detail | The integer | read-only | Additional information about the event |
eventPhase | The integer | read-only | Represents the stages of invoking the event handler: 1 for capture, 2 for destination, and 3 for bubbling |
preventDefault() | function | read-only | Default behavior for canceling events. This method can only be called if cancelable is true |
stopImmediatePropagation() | function | read-only | Used to cancel all subsequent event capture or event bubbling and prevent the invocation of any subsequent event handlers (new in DOM3 Events) |
stopPropagation() | function | read-only | Use to cancel all subsequent event capture or event bubbling. This method can only be called if bubbles is true |
target | The element | read-only | Event goals |
trusted | Boolean value | read-only | True indicates that the event was generated by the browser. False indicates that the event was created by the developer in JavaScript (new in DOM3 Events) |
type | string | read-only | The type of event that is fired |
View | AbstractView | read-only | Abstract views related to events. Is equal to the window object where the event occurred |
Inside the event handler, the this object is always equal to the value of currentTarget, while target contains only the actual target of the event.
// add the click event to the body, BTN document.body. Onclick = function(event) {console.log(event.currenttarget === document.body); // true console.log(this === document.body); // true console.log(event.target === document.getElementById("myBtn")); // true };Copy the code
-
The preventDefault() method is used to prevent the default action for a particular event. (Cancelable must be true)
-
The stopPropagation() method is used to immediately stop the event stream from propagating through the DOM structure, canceling subsequent event capture or bubbling.
User interface events
- Load: Triggered at the window when the page has finished loading
window.addEventListener("load", (event) => { console.log("Loaded!" ); });Copy the code
- Error: Raised when a JavaScript error occurs on a window, or when a element cannot load the specified image
- Select: Triggered in a text box ( or textarea) when the user selects one or more characters.
- Resize: Triggered when a window or pane is scaled.
- Scroll: Triggered on an element that contains a scrollbar when the user scrolls it. The element contains the scroll bar for the loaded page. Most HTML events are related to window objects and form controls.
window.addEventListener("scroll", (event) => { if (document.compatMode == "CSS1Compat") { console.log(document.documentElement.scrollTop); } else { console.log(document.body.scrollTop); }});Copy the code
“Event”
- Blur: Triggered when an element loses focus. This event does not bubble up
- Focus: Fires when the element gains focus. This event does not bubble up
Mouse and scroll events
- Click: Triggered when the user clicks the primary mouse key (usually the left) or presses the enter key on the keyboard.
- Dblclick: Triggered when the user double-clicks the primary (usually left) mouse button.
- Mousedown: Triggered when the user presses any mouse key. This event cannot be triggered by the keyboard.
- Mouseenter: Triggered when the user moves the mouse cursor from outside the element to inside it.
- Mouseleave: Triggered when the user moves the mouse cursor from inside an element to outside it.
- Mousemove: Triggers repeatedly as the mouse cursor moves over the element.
- Mouseout: Triggered when the user moves the mouse cursor from one element to another.
- Mouseover: Triggered when the user moves the mouse cursor from outside the element to inside it.
- Mouseup: Triggered when the user releases the mouse key.
. . . I’ll write it next time. There’s too much
Chapter 19 – Form Scripts
The target
- Understand form basics
- Text box validation and interaction
- Use other form controls
basis
- Web forms are represented as a
-
Built-in property methods
- Action: The requested URL, equivalent to the HTML action property.
- Enctype: The encoding type of the request, equivalent to the HTML encType attribute.
- Method: The method type of an HTTP request, usually “get” or “POST”, equivalent to the HTML method attribute.
- Reset () : Resets form fields to their default values.
- Submit () : Submits the form.
-
Submit the form && reset the form
let form = document.getElementById("myForm"); // submit the form form.submit(); // Reset the form form.reset();Copy the code
-
methods
- Focus () and blur(), focus
/ / out-of-focus document forms [0]. Elements [0]. The blur ();Copy the code
-
The event
- focus, blur, change
textbox.addEventListener("change", (event) => { let target = event.target; }); Copy the code
The text box
- input
// size width <input type="text" size="25" maxLength ="50" value="initial value">Copy the code
- textarea
Cols ="5"> Initial value</textarea>Copy the code
- Select text
// 1
let textbox = document.forms[0].elements["textbox1"];
textbox.select();
// 2
textbox.addEventListener("focus", (event) => {
event.target.select();
});
Copy the code
Select box
- Select and option
<select name="location" id="selLocation">
<option value="Sunnyvale, CA">Sunnyvale</option>
<option value="Los Angeles, CA">Los Angeles</option>
<option value="Mountain View, CA">Mountain View</option>
<option value="">China</option>
<option>Australia</option>
</select>
Copy the code
- Select the first one
selectbox.options[0].selected = true;
Copy the code
- Element contenteditable
<div contenteditable></div>Copy the code
Chapter 24 – Network Requests and Remote Resources
The target
- Use the XMLHttpRequest object
- Handles the XMLHttpRequest event
- Source domain Ajax restrictions
- Fetch API
- Streams API
XMLHttpRequest
// create let XHR = new XMLHttpRequest(); // 0: before open, 1: after open 2. After send 3. Complete XHR. Onreadystatechange = function () {if (XHR. ReadyState = = 4) {if ((XHR) status > = 200 && XHR. Status < 300) | | xhr.status == 304) { alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); }}}; Xhr. open("get", "example.php", false); // send request body, no null xhr.send(null) is required;Copy the code
- Request header
- Accept: The type of content that the browser can process.
- Accept-charset: character set that can be displayed by the browser.
- Accept-encoding: Encoding type of compression that the browser can handle.
- Accept-language: indicates the Language used by the browser.
- Connection: Connection type between the browser and the server.
- Cookie: Cookie set on the page.
- Host: domain of the page that sent the request.
- User-agent: indicates the character string of the User Agent of the browser.
xhr.setRequestHeader("MyHeader", "MyValue");
Copy the code
- FormData
let data = new FormData();
data.append("name", "Nicholas");
Copy the code
- timeout
xhr.timeout = 1000; Xhr. ontimeout = function() {alert("Request did not return in a second."); };Copy the code
-
CORS are shared across source resources
-
Preview the request
- Request to send using the OPTIONS method
-
JSONP
- JSONP is short for “JSON with padding”
function handleResponse(response) {
console.log(`
You're at IP address ${response.ip}, which is in
${response.city}, ${response.region_name}`);
}
let script = document.createElement("script");
script.src = "http://freegeoip.net/json/?callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
Copy the code
Fetch
Let r = fetch('/bar', {method: 'POST', // Body: payload, headers: jsonHeaders}); console.log(r); // Promise <pending>Copy the code
fetch('bar.txt')
.then((response) => {
console.log(response.status); // 200
console.log(response.statusText); // OK
response.text().then((data) => {
console.log(data);
});
});
Copy the code
- interrupt
let abortController = new AbortController(); fetch('wikipedia.zip', { signal: abortController.signal }) .catch(() => console.log('aborted! '); SetTimeout (() => abortController.abort(), 10); // It has been interruptedCopy the code
Web Socket
let socket = new WebSocket("ws://www.example.com/server.php"); let stringData = "Hello world!" ; let arrayBufferData = Uint8Array.from(['f', 'o', 'o']); let blobData = new Blob(['f', 'o', 'o']); socket.send(stringData); socket.send(arrayBufferData.buffer); socket.send(blobData); Onmessage = function(event) {let data = event.data; // Perform some operations on the data};Copy the code
- state
- Websocket.opening (0) : The connection is being established.
- Websocket.open (1) : the connection has been established.
- Websocket.closing (2) : The connection is CLOSING.
- Websocket.close (3) : The connection is closed.
- Other events
- Open: Triggered when a connection is successfully established.
- Error: Triggered when an error occurs. The connection could not survive.
- Close: Triggered when the connection is closed.
security
- Require SSL access to resources that can be accessed by Ajax.
- Each request is required to send a token calculated according to the convention algorithm. Note that the following measures are not effective against CSRF attacks.
- Ask for A POST request instead of a GET request (easily modified request method).
- Verify the source with the source URL (source urls are easy to forge).
- Cookie-based authentication (also easy to forge).