Chapter 1 What is JavaScript

background

  • ECMAScript: JavaScriptTo achieve theECMAScript.ECMAScriptDescribe the syntax, type, etc of the language
  • DOM(Text Object Model) : DOM abstracts the entire page as a set of hierarchical nodes that control the content and structure of the page by creating a tree that represents the document
  • BOM(Browser Object Model) : A window used to support accessing and manipulating a browser

Chapter 2 JavaScript in HTML

Introduction to script tags

  • scriptYou can load in-line code and external files, which is more maintenance friendly
  • deferasyncCan change the load order, the difference is the formerscriptThe loading sequence between labels is fixed inDOMContentLoadedBefore loading, which is performed in an indeterminate load order before the page load event
  • typeProperties formoduleModularity in ES6 can be achieved

Chapter 3 Language foundation

Basic grammar

  • Variable declarations

    scope variability note
    var Functions; Scope enhancement; variable Repeatable declaration
    let Block level; Scope cannot be increased; variable Non-repeatable declaration
    const block-level immutable
  • The data type

    Basic data types Undefined, Null, Boolean, Nunber, String, Symbol
    Complex data types Object

    Undefined Undefined, Null Undefined

  • The integer conversion

    function string note
    Number() Non-empty =>NaN “” => 0
    parseInt() Non-empty => first few digits of a number “” => NaN Contains a second argument specifying the base number
    parseFloat() As above, convert to floating point Ignore the base
  • Template literals tag functions

    Const a = 3 const b = 4 // String ' '// function simpleTag(strings,... expressions) { ... } const result simpleTag `${a} + ${b} = ${a+b}`Copy the code

    String.raw Raw character String

  • Built-in Symbol

    Symbol is familiar with describe
    Symbol.asyncIterator This method returns the object’s default AsyncIterator, used by the for-await-of statement
    Symbol.hasInstance This method determines whether a constructor object recognizes an object as an instance of it
    Symbol.isConcatSpreadable The return value is decided to use array.prototype.concat () to flush its Array elements
    Symbol.iterator This method returns the default iterator for the object. Used by for-of statements
    Symbol.match This method matches strings with regular expressions, used by the string.prototype.match () method
    Symbol.replace This method replaces the matched substring in a string. Used by the string.prototype.replace () method
    Symbol.search This method returns the index in the string that matches the regular expression. Used by the string.prototype.search () method
    Symbol.split This method splits the string at the index position that matches the regular expression. Used by the string.prototype.split () method
    Symbol.species This function is used as a constructor to create derived objects
    Symbol.toPrimitive This method converts the object to the corresponding original value. Used by the ToPrimitive abstract operation
    Symbol.toStringTag This string is used to create the default string description of the object. By the method of built-in Object. The prototype. The toString () is used
    Symbol.unscopables All and inherited attributes of the object are excluded from the with environment binding of the associated object
  • The operator

    The operator describe
    Unary operator ++, –; After ++, –; Unary plus, minus
    An operator ~, &,
    Boolean operator ! , &&,
    Multiplicative operator *, /, %
    Exponential operator 支那
    The additive operator +, –
    Relational operator >, <, >=, <=
    Equality operator = =,! === =! = = =
    Conditional operator ? :
    The assignment operator = (compound assignment)
    Comma operator , (multivariable initialization)
  • statements

    statements describe
    If statement Logical decision statement
    do-while Only the sex cycle
    while When the circulation
    for… i Determine the circulation
    for… in Enumerates non-symbolic key properties in an object
    for… of Iterates through the iterable’s elements
    Break, continue Break breaks the loop, and continue breaks the loop
    swich Branch statements, indeed break is penetrable
    Label statement, with Not commonly used

Chapter 4 variables, scopes, and Memory

  • Raw and reference values

    • Primitive values are the simplest data and you can’t add dynamic attributes
    • A reference value is an object composed of multiple values that can be added with dynamic attributes
  • Duplicate values

    • The original value itself is copied to the location of the new variable
    • A reference copy is actually a reference (essentially a pointer), and a change on one object is reflected on another object
  • Passing parameters

    • Arguments to all functions in ECMAScript are passed by value
  • Determine the type

    • typeofDetermines whether a variable is of primitive type
    • instanceofJudge archetypal relation
  • Execution context and scope

    • Variable query from inside out
  • The garbage collection

    way describe
    Mark sweep When the garbage collector runs, it marks all variables stored in memory, then unmarks all variables in context and those referenced by variables in context, and then the garbage collector does a memory cleanup
    Reference counting For each value, the number of times it is referenced is recorded. 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 1. If the variable holding a reference to that value is overwritten by another value, the number of references is decreased by 1. When a value has zero references, it is no longer accessible and can safely reclaim its memory.

Chapter 5 basic reference types

  • Date

    • Date.parse()
    • Date.UTC()
    • The native Date display is browser-based, and dayJS is available in the project
  • RegExp

    • String creationlet expression = /pattern/flags
    • Object creationlet expression = new RegExp()
    Instance methods describe
    exec() Used with capture groups
    test() Tests whether the patterns match
  • Raw data wrapper type

    methods
    new Boolean()
    new Number() ToFixed (), isInteger ()
    new String()
  • String manipulation methods

    String manipulation methods describe
    concat() Concatenated string
    str.slice(beginIndex[, endIndex]) Negative argument String length plus negative argument value
    str.substr(start[, length]) The first negative argument value is the length of the string plus the value, and the second negative argument value is converted to 0
    str.substring(indexStart[, indexEnd]) All negative parameter values are converted to 0
    IndexOf (), lastIndexOf ()
    StartsWith (), endsWith(), and includes()
    trim()
    repeat()
    PadStart () and padEnd ()
    ToLowerCase (), toLocaleLowerCase(), toUpperCase(), and toLocaleUpperCase()
    Match (), search(), replace() The incoming regular
    localeCompare()
  • Singleton built-in object

    note
    Global URL encoding method, eval() The browser implements the Window object as a proxy for the Global object
    Math Min (), Max (), ceil(), floor(), round()random()

Chapter 6. Collection reference types

  • Object

    • Create: New Object() and literals
    • Attribute values:.[]
  • iterable

    create methods
    common Iteration methods: keys(), values(), entries() iteration: every(), filter(), forEach(), map(), some()
    Array New Array(), literals, array.form, array.of Check Array: array.isarray () : fill(), copyWithin() convert: ToLocaleString (), toString() and valueOf() tail methods: push(), pop() header methods: unshift(), shift() sort: reverse() and sort() search: IndexOf(), lastIndexOf(), and includes() operations: concat(), slice(), splice() merge: reduce(), reduceRight()
    Finalize the design array Create view DataView or Stereotype Array on ArrayBuffer (XxxyyArray)
    Map new Map() Basic: Set (), get(), has(), delete(), clear() and property size Iteration methods: keys(), values(), entries()
    WeakMap New WeakMap() and Key are objects An iterative
    Set new Set() Basic: add(), has(), delete()
    WeakSet new WeakSet() An iterative

Chapter 7 iterators and Generators

  • Iterations can have no termination conditions, loops can’t

  • Iterator pattern: Implements the formal Iterable interface and can be consumed through the Iterator

  • Custom iterators

    class Count { constructor(limit) { this.limit = limit; } [Symbol.iterator]() { let limit = this.limit, count = 1; return { next() { if(count <= limit) { return { done: false, value: count++}; }else { return { done: true, value: undefined }; }}, return() {// throw break to call console.log("breal/throw"); return { done: true }; } } } } let count = new Count(10); for(let i of count) { if(i > 5) { break } console.log(i); } for(let i of count) { console.log(i); }Copy the code
  • Generator: A generator is a function in the form of a function whose name is preceded by an asterisk (*) to indicate that it is a generator. The yield keyword causes the generator to stop and start execution. Yield * really just serializes an iterable into a series of values that can be produced individually

  • Unlike iterators, all generator objects have a return() method, which forces the generator into a closed state

Chapter 8 objects, classes, and Object-oriented programming

  • Create objects: New Object() and literals

  • For the data property, it contains different, Enumerable, Writable and value properties, and for the accessor property, it contains different, Enumerable, GET and set properties.

  • Object.assign() merges objects

  • The prototype pattern

  • Prototype chain (for constructors)

    • implementation

      function Parent1() {
          this.name = 'parent1';
          this.play = [1, 2, 3]
      }
      function Child1() {
          this.type = 'child2';
      }
      Child1.prototype = new Parent1();
      console.log(new Child1());
      Copy the code
    • Advantages: Implementation of inheritance

    • Disadvantages: reference value sharing, parent class parameter passing

  • Embezzled constructors

    • implementation

      function Parent1(){ this.name = 'parent1'; } Parent1.prototype.getName = function () { return this.name; } function Child1(){ Parent1.call(this); this.type = 'child1' } let child = new Child1(); console.log(child); // No problem console.log(child.getname ()); / / complainsCopy the code
    • Advantages: Can transfer parameters

    • Disadvantages: Subclasses cannot inherit methods previously defined by their parent class

  • Combination of inheritance

    • implementation

      function Parent3 () { this.name = 'parent3'; this.play = [1, 2, 3]; } Parent3.prototype.getName = function () { return this.name; } function Child3() {Parent3() parent3.call (this); this.type = 'child3'; } // call Parent3() child3. prototype = new Parent3(); / / hang up the constructor manually, pointing to his own constructor Child3. The prototype. The constructor = Child3; var s3 = new Child3(); var s4 = new Child3(); s3.play.push(4); console.log(s3.play, s4.play); Console.log (s3.getName()); // Output 'parent3' console.log(s4.getName()); // Normal output 'parent3'Copy the code
    • Advantages: Compensates for prototype chains and stolen constructors, retains the ability of the Instanceof operator and isPrototypeOf() method to recognize synthesized objects

  • Original type inheritance (for common objects)

    • implementation

      let parent4 = { name: "parent4", friends: ["p1", "p2", "p3"], getName: function() { return this.name; }}; let person4 = Object.create(parent4); person4.name = "tom"; person4.friends.push("jerry"); let person5 = Object.create(parent4); person5.friends.push("lucy"); console.log(person4.name); console.log(person4.name === person4.getName()); console.log(person5.name); console.log(person4.friends); console.log(person5.friends);Copy the code
    • Disadvantages: Masking properties of the same name on prototype objects, multiple instances of reference type properties pointing to the same memory

  • Parasitic inheritance

    • Implementation:

      let parent5 = { name: "parent5", friends: ["p1", "p2", "p3"], getName: function() { return this.name; }}; function clone(original) { let clone = Object.create(original); clone.getFriends = function() { return this.friends; }; return clone; } let person5 = clone(parent5); console.log(person5.getName()); console.log(person5.getFriends());Copy the code
    • Disadvantages: Two calls to the parent constructor cause waves

  • Parasitic combinatorial inheritance

    • Implementation:

      function clone (parent, Prototype = object.create (parent. Prototype); child.prototype.constructor = child; } function Parent6() { this.name = 'parent6'; this.play = [1, 2, 3]; } Parent6.prototype.getName = function () { return this.name; } function Child6() { Parent6.call(this); this.friends = 'child5'; } clone(Parent6, Child6); Child6.prototype.getFriends = function () { return this.friends; } let person6 = new Child6(); console.log(person6); console.log(person6.getName()); console.log(person6.getFriends());Copy the code
  • class

    • The concepts of stereotypes and constructors are still behind it

Chapter 9 Agency and Reflection

  • To create the agent

    // Const proxy = new proxy (target, handle); // Const {proxy, REVOKE} = proxy. Revocable (target, handle); . revoke()Copy the code
  • capture

    capture trigger
    get() Is called in an operation to get the value of a property
    set() Is called in an operation that sets the value of a property
    has() Called in the IN operator
    defineProperty() Called in Object.defineProperty()
    getOwnPropertyDescriptor() In Object. GetOwnPropertyDescriptor () is invoked
    deleteProperty() Is called in the delete operator
    ownKeys() Called in object.keys () and similar methods
    getPrototypeOf() In the Object. GetPrototypeOf ()
    setPrototypeOf() Called in Object.setPrototypeof ()
    isExtensible() Called in Object.isextensible ()
    preventExtensions() Called in Object.preventExtensions()
    apply() Called when a function is called
    construct() Is called in the new operator
  • The agent is insufficient

    • The this of the proxy object points to itself
    • Some ECMAScript built-in type proxy objects do not have certain internal slots
  • The proxy pattern

    • Monitor objects by capturing operations such as GET, SET, and HAS
    • The agent’s internal implementation is not visible to external code
    • Allows or rejects assignments in set() depending on the value assigned (returns a Boolean value)
    • Function and constructor parameters are examined using apply() and construct()

Chapter 10 functions

  • Functional form

    • Function declaration

    • Functional expression

      • The scope does not improve
    • Arrow function

      • shorthand(a), the return value
      • There is noarguments
      • externalthis
    • Function constructor

  • parameter

    • Strict mode Arguments cannot be modified
    • The default parameters
    • .The parameters are merge parameters, and the arguments are deconstruction parameters
    • new.targetCan be used for function instantiation
  • Function method

    • Apply the second parameter array

    • Call The second one is passed separately

      • Bind creates a new instance of the function, the second array of arguments
  • closure

    • A function that references a variable in the scope of another function, usually implemented in a nested function

Chapter 11 is about scheduling and asynchronous functions

  • Asynchronous programming: callback function => Promise => await/async

  • Promise

    • Create:new Promise(),Promise.resolve,Promiste.reject
    • PromiseStatus: Pending, depressing, rejected
    • Example methods: then(), catch(), finally()
    • Promise. All () and Promise. Race ()
  • async/await

Chapter 12 BOM

  • Browser Object Model (BOM)

    object details Properties, methods
    window ECMAScript Global object, JavaScript interface for browser window Window size, viewport scrolling, Open (), timer, system dialog box
    location Information about loading documents in the current window, as well as general navigation functions Search, assign(), reload()
    navigator The properties of the Navigator object are typically used to determine the type of browser The plugins, registerProtocolHandler ()
    screen Information about the client display outside the browser window
    history Navigation history of the user since the current window was first used Go (), back(), forward()

Chapter 13 Client Detection

  • Ability testing: first general, then special
  • UserAgent: navigator.userAgent inaccurate and tamper with
  • Software and hardware detection: Navigator and Screen

Chapter 14 DOM

  • There are 12 Node types in the DOM, all of which inherit from a Node type

DOM node describe Properties and methods
The Node type All Node types inherit from Node types NodeType, nodeName, nodeValue, childNodes

AppendChild (), insertBefore(), replaceChild(), cloneNode(), normalize()
The Document type HTMLDocument inherit the Document DocumentElement, Body, docType, Title, implementation

GetElementById (), getElementsByTagName(), write(), writeln(), open(), close()
Element type Expose the ability to access element label names, child nodes, and attributes The nodeName or tagName attribute gets the element’s tagName (without custom attributes), attributes, and childNodes

GetAttribute (), setAttribute(), removeAttribute(), document.createElement()
The Text type Plain text, no HTML code nodeValue

Document.createtextnode (), Normalize (), splitText()
The Comment type annotation All string operations on a Text node except splitText()

document.createComment()
CDATASection type CDATA blocks that are unique to XML document.createCDataSection()
DocumentType type Contains information about the document type Name, entities and notations
DocumentFragment type There is no corresponding representation of type, temporary container, in the tag document.createDocumentFragment()
Attr type Element data is represented in the DOM by the Attr type Name, value, and specified

document.createAttribute()
  • DOM programming

    • Dynamic script
    • Dynamic style
    • The operating table
    • Use NodeList (dynamic changes, recording initial values)
  • MutationObserver

    let observe = new MutationObserver((mutationRecords) => console.log('DOM was mutated', mutationRecords));
    observe.observe(document.body, { attributes: true })
    document.body.className = "foo";
    Copy the code

Chapter 15 DOM Extensions

  • Selectors API

    methods describe
    querySelector() Receives CSS selector arguments
    querySelectorAll() It also takes a parameter to query and returns all matching nodes
    matches() Receives a CSS selector argument that checks if an element matches a rule
  • Element Traversal API

    attribute describe
    childElementCount Spaces between elements are not treated as blank nodes
    firstElementChild
    lastElementChild
    lastElementChild
    previousElementSibling
    nextElementSibling
  • HTML5

Methods, attributes describe
getElementsByClassName() Accepts one or more class names and returns the NodeList containing the elements of the corresponding class in the class name
ClassList properties Add (), contains(), remove(), toggle()
focus()
ReadyState attribute Whether the document is loaded successfully: Loading, complete
CompatMode properties Indicates what render mode the browser is currently in
The head properties The element pointing to the document
CharacterSet properties
data- User-defined attribute, dataset acquisition
InnerHTML properties, outerHTML properties
With insertAdjacentText insertAdjacentHTML () ()
scrollIntoView() Scroll the browser window or container element to include the element into the viewport
  • Special extension

    Properties, methods describe
    Children attribute Contains only the Element’s Element type child nodes
    The contains (), compareDocumentPosition ()
    The innerText, outerText
    scrollIntoViewIfNeeded()

Chapter 16 DOM2 and DOM3

  • DOM2 provides namespace-specific versions for most DOM1 methods

    • Changes to Node: isSameNode() and isEqualNode()
    • Document changes: XxxNs, importNode(), defaultView, Document.implementation
    • Element changes: XxxNs
    • NamedNodeMap changes: XxxNs
    • The change of the DocumentType
    • Changes to inline panes: contentDocument, contentWindow
  • style

    • Any HTML element that supports the style attribute will have a corresponding style attribute in JavaScript, which is an instance of the CSSStyleDeclaration type
    • DOM2 Style adds the getComputedStyle() method to document.defaultView
    • The CSSStyleSheet type inherits StyleSheet, both using elements and stylesheets defined by elements, and the CSSRule type represents a rule in the StyleSheet
  • traverse

    • NodeIterator

      const div1 = document.getElementById("div1")
      const iterator = document.createNodeIterator(div1, NodeFilter.SHOW_ELEMENT, null.false)
      let node = iterator.nextNode()
      while(node ! = =null) {
          console.log(node.tagName);
          node = iterator.nextNode()
      }
      Copy the code
    • TreeWalker is more flexible with NodeIterator, previousSibling(), nextSibling(), firstChild(), lastChild(), parentNode(), currentNode

  • The scope of

    • To create createRange(), simply choose to set the range selectNode() or selectNodeContents()
    • SetStart () and setEnd ()
    • Operation: DeleteContents (), extractContents(), cloneContents(), insertNode(), surroundContents(), collapse(), compareBoundaryPoints(), C LoneRange, detach () ()

Chapter 17 Events

  • Flow of events

  • Event handler

    • HTML event handler

      / / way<input id="mybtn" type="button" value="Click me" onclick="console.log('bbb')">2 / / way<input id="mybtn" type="button" value="Click me" onclick="showMessage()">
      <script>
          function showMessage() {
              console.log('bbb')}</script>    
          
      Copy the code
    • DOM0 event handler

      // Add events
      const mybtn = document.getElementById("mybtn");
      mybtn.onclick = () = > { console.log("aaa"); }
      
      // Remove the event
      mybtn.onclick = null
      Copy the code
    • DOM2 event handler

    // Add events
    const mybtn = document.getElementById("mybtn");
    function showMessage() { 
        console.log("aaa"); 
    }
    mybtn.addEventListener("click", showMessage, false) 
    
    // Remove the event
    mybtn.removeEventListener("click", showMessage, false) 
    Copy the code
    • IE event handlers: attachEvent() and detachEvent()
  • The event object

  • DOM event object, callback function parameters Event: Type, eventPhase, preventDefault(), stopPropagation()

  • IE event object, the Event object is just a property of the Window object

  • The event type

    • User interface events: Load, Unload, abort, error, Select, resize, Scroll
    • Focus events: Blur, DOMFocusIn, DOMFocusOut, Focus, focusIn
    • Mouse and wheel events: Click, dblclick, mousedown, mouseEnter, mouseleave, Mousemove, mouseover, mouseup, mouseWheel
    • Keyboard and input events: keyDown, textInput(keypress), keyUp
    • Composite events: comPOSItionStart, COMPOSItionUpdate, comPOSItionEnd
    • HTML5 events: ContextMenu, beforeUnload, DOMContentLoaded, eadyStatechange, PagesHow with PageHide, Hashchange
    • Device events: OrientationChange, DeviceOrientation, Devicemotion
    • Touch and gesture events: TouchStart, TouchMove, Touchend, TouchCancel, geSTUrestart, geSTUrechange, geSTUreend
  • Memory and Performance

  • Event delegate: Event delegate utilizes event bubbling to manage one type of event with only one event handler

  • Simulation of events

    • The document.CreateEvent () method creates an event object, UIEvents, MouseEvents, HTMLEvents, HTMLEvents, CustomEvent

      const mybtn = document.getElementById("mybtn");
      mybtn.onclick = () = > { console.log("aaa"); }
      const event = document.createEvent("MouseEvents");
      event.initEvent("click");
      mybtn.dispatchEvent(event);
      Copy the code

Chapter 18 Animation and Canvas Graphics

  • JavaScript animation: requestAnimationFrame
  • Canvas: getContext(‘2d’), fillRect(), strokeRect(), clearRect(), fillText(), strokeText()
  • WebGL has so much content that I have to find a tutorial to relearn it

Chapter 19. Form Scripts

  • Get the form, submit the form, reset the form
  • Form events: Select text, input filtering
  • Form serialization: string concatenation

Chapter 20 JavaScriptAPI

  • The Atomics API ensures that JavaScript operations on SharedArrayBuffer are thread-safe
  • The Encoding API is primarily used to convert strings to stereotyped arrays
  • The File API and Blob API are designed to give Web developers secure access to files on the client machine
  • The Notifications API is used to display Notifications to the user
  • The Page Visibility API is designed to provide developers with information about whether a Page is visible to the user
  • The Streams API addresses how Web applications consume ordered chunks of information
  • The timing API, where all page-related metrics, both defined and defined in the future, reside on the window.performance object
  • The Web Cryptography API describes a set of Cryptography tools

Chapter 21 error Handling and debugging

  • Try/catch statements
  • throw

Chapter 22 deals with XML

  • DOMParser/ XMLSerializer

Chapter 23 JSON

  • Syntax: simple values, objects, arrays
  • Json.stringify (), which can be changed with oJSON()
  • JSON.parse()

Chapter 24 network Requests and Remote Resources

  • XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("get"."xxx".false);
xhr.send(null);
Copy the code
  • Fetch API

    let jsonHeader = new Headers({
        mode: "cors",
    })
    
    fetch("xxx", {
        headers: jsonHeader,
    }).then(res= > {
        console.log(res);
    })
    Copy the code
  • Unload Sends requests: Beacon API

Chapter 25 client Storage

  • Cookie: server setting, domain specific, document.cookie

  • Web Storage

    • sessionStorage
    • localStorage
  • IndexedDB has many of the same limitations as Web Storage

let db,
    request,
    version = 1;
request = indexedDB.open("admin", version);
request.onerror = (e) = > {
    alert(`Failed to open ${e.targer.errorCode}`);
}    
request.onsuccess = (e) = > {
    db = e.target.result;
    console.log(db);
}
Copy the code

Chapter 26 modules

  • CommonJS(Node.js uses a slightly modified version of CommonJS)

    • module.exports/exports
    • require
  • AMD browser is the target execution environment

  • ES Module

    • export
    • import

Chapter 27 worker threads

  • Dedicated worker threads: Create dedicated worker threads to perform tasks other than the page thread
  • Shared worker threads: Can be accessed by multiple trusted execution contexts
  • Service worker threads: Can intercept outgoing requests and cache responses

Chapter 28 best Practices

  • Focus on specific projects