This is the 12th day of my participation in the August Text Challenge.More challenges in August

1. Know javascript

  • JavaScript is a loose object-oriented language

  • JavaScript is now composed of ECMAScript(core)+ Document Object Model (BOM)+ Browser object Model (DOM).

  • The JavaScript we typically work with runs on top of a Web browser. Web browsers have no dependency on ECMAScript. Web browsers build more sophisticated scripts (such as adding bom and DOM) based on ECMAScript.

    • A similar hosting environment is Node
  • ECAMScript specifies what to do

    • grammar
    • type
    • statements
    • The keyword
    • Reserved words
    • The operator
    • object

    Summary: Provides core language functionality

  • Document Object Model DOM

    • The Document Object Model is an API used to manipulate HTML structures

    • The BASIS for DOM manipulation of HTML is that the browser renders a web page as a DOM tree, which maps the entire page into a multi-tiered structure.

    • We use the API provided by DOM to manipulate this multi-level structure. Easily add, delete, change, and check DOM elements.

    • The main features of DOM are:

      1. Mapping HTML structure
      2. DOM Views: Defines an interface for tracking Views of different documents, such as documents before and after CSS is applied
      3. DOM Events: Defines the interface for Events and event handling
      4. DOM Style: Defines an interface for applying styles to elements based on CSS
      5. DOM Traversal and Range: Defines the interface for traversing and manipulating the document tree
    • Summary: provides access and operation of web content methods and interfaces

  • Browser object model BOM

    • The browser object model is an API applied to operations on the browser window
      • You can manipulate parts of the page that are not displayed by the browser
      • BOM only deals with browser Windows and frames
      • Specific extensions are:
        • The ability to pop up new browser window
        • The ability to move, zoom, and close browser Windows
        • A navigator that provides browser details
        • A Location object that provides details about the page loaded by the browser page
        • Screen object that provides details about the resolution of the user’s display
        • Support for cookies
        • Custom objects like XMLHttpRequest and IE’s ActiveXObject
    • Summary: provides methods and interfaces for interacting with browsers

2. Use JavaScript in HTML

2.1 script element

The interpreter executes from top to bottom, starting from the beginning. The following code or elements are not allowed to execute or display until the execution is complete. Whether it’s embedded JS, externally referenced JS, or HTML elements.

External imported JS files can be cached by the browser

  • Common attributes of script elements:

    1. Async: optional
      • Indicates that the script should be downloaded immediately, but should not interfere with other actions on the page. Only valid for external resources
    2. Defer: optional
      • Indicates that the script is deferred until the document is fully parsed and displayed. Only valid for external resources.
    3. SRC: optional
      • Represents the path to an external file
    4. Type: Mandatory, default is ‘text/javascript’
      • The content type (also known as MIME type) that represents the scripting language in which the code was written
      • The MIME type used when the server actually transmits JS files is usually application/ X-javascript or Application /javascript
  • About defer – The deferred script

    • Notify the browser to download it immediately (just like synchronizing external JS immediately, but with a delay). The defer script will wait for the HTML parser to finish parsing and execute. The DOMContentLoaded event is executed immediately after the defer script executes.
    • Leaving the defer script at the bottom of the page is the best option.
  • About Async — Asynchronous scripts

    • Notify the browser to download the file immediately, but continue until the file has been downloaded and the HTML parser executes it
      • There are two scenarios here
        1. The HTML parser has finished parsing the DOM tree
          1. The DOMContentLoaded event is raised if parsing is complete. Then the async script is executed
        2. The HTML parser is not fully parsed by the DOM tree
          1. If parsing is not complete, parsing is paused to execute the async script.
      • So the async script must be executed before the page load event, but may be executed before or after the DOMContentLoader.
      • The purpose of async is to prevent pages from waiting for scripts to download and execute, so it is best not to manipulate DOM elements in async scripts.
  • A couple of little things

    With the SRC attribute

2.2 noscript elements

  • Noscript elements solve the problem of:

    1. Browsers do not support scripting
    2. Browsers support scripting, but browsers disable it.
    // If both cases occur, the following HTML is displayed on the page at the same time
    <noscript>
       <p>Your site does not support JavaScript</p>
    </noscript>
    <h1>Ha ha ha ha</h1>
    // Is useful in single-page applications
    Copy the code
  • Disabling JS ensures that basic features, such as structure and style, remain elegantly degraded and progressively enhanced in design.

3. Ecmascript basic syntax

3.1 Basic Concepts

Describing the most basic working principles of a language involves the syntax, operators, data types, built-in functions, and other basic concepts used to build complex solutions

3.2 grammar

  • Case sensitive
    • Everything in ECMAScript (variables, function names, operators) is case sensitive
  • identifier
    • Refers to the name of a variable, function, attribute, or function parameter
    • Naming rule 1: The first character must be a letter, underscore, or dollar sign
    • Naming rule 2: Other characters can be letters, underscores, dollar signs, or numbers
    • Naming convention: EcMAScript identifiers are in camel case format.
    • Keywords and reserved words cannot be used as identifiers
  • Note:
    • Single-line comments
    • Multiline comment
  • Strict mode
    • Ecmascript introduces the concept of strict schemas. Strict mode defines a different parsing and execution model for JavaScript
    • Strict mode can be enabled for the entire script, or it can be enabled for code in the function scope first within the function body
    • “Use strict” is a compilation instruction that tells the JavaScript engine to switch to strict mode.
  • Keywords and reserved words
    • One thing to note here: In strict mode, eval and arguments cannot be used as identifiers and attribute names

3.3 Data Types

3.3.1 Basic Concepts

Ecmascript has five simple (basic) data types: Undefined, Null, Boolean, Number, and String.

Complex data type: Object.

3.3.2 checking the data typeof a variable — the typeof operator

  • “Undefined” — this value is undefined
  • “Boolean” — This value is a Boolean value
  • “String” — This value is a string
  • “Number” — This value is a numerical value
  • “Object” — This value is either null or regular
  • “Function” — This value is a function

If we see typeof (MSG), we can remove the parentheses.

(Special case) Typeof the re returns function in Safari 5- Chrom7 – when typeof the re is used

3.3.3 undefined type

  • Has not been defined

  • After a variable is declared, it is automatically assigned undefined if it is not assigned.

3.3.4 null

  • Null pointer object

3.3.5 boolean

  • Boolean has only two true or false values
  • To convert a value to a Boolean, call the transformation function Boolean()
  • Boolean() Transformation function rule
  • ,
The data type The result is true The result is false
boolean true false
string Any non-empty string “” (empty string)
number Any non-zero numeric value (including infinity) 0 and NaN
object Any object null
undefined undefined

3.3.6 number type

  • The number type represents both integer and floating point types
  1. Numeric literals are in decimal and octal and hexadecimal
  • The first digit of an octal literal must be 0, followed by digits ranging from 0 to 7. Otherwise, it will be parsed in decimal
    • For example, var num = 070 // octal 56
    • For example, var num = 079 // Invalid octal resolves to 79
    • Octal literals are not valid in strict mode
  • The first two hexadecimal literals must be 0x, followed by 0 to 9 and A(A) to F(F). — Otherwise an error will be reported.
  1. Floating point value

    • A floating point number must contain a decimal point followed by at least one digit. 0. XXX 0 can be omitted.

    • If there are no integers behind the decimal point, all zeros, it will be resolved to integers.

    • Floating-point values take up twice as much space as integer values, and ECMAScript cleverly converts floating-point numbers followed by zeros to integers.

  2. Range of values

    • Number.MAX_VALUE and number. MIN_VALUE represent the maximum and minimum values of the JS value range respectively
    • To determine if a number is between the minimum and maximum, use the isFinite(XXX) function to determine if it is between the range
    • If this number is out of range, it’s Infinity or -infinity
  3. NaN

    • A special value (Not a Number) that returns an operand that was supposed to return a value but did Not.
    • Anything that involves a NaN is a NaN
    • Ecmascript defines the isNaN function to determine whether a data is a NaN

Both isFinite() and isNaN(), as well as the – * / operation on a value, first attempt to convert the parameter/operation data to a value. If the conversion succeeds, it is evaluated numerically; if the conversion fails, NaN is returned directly.

If it is an object, the valueOf() method of the object is called first. If it returns a value, it is evaluated as usual. If not, the toString() method is called, and if not, NaN is returned.

  1. Numerical conversion methods

    • In addition to calling the valueOf and toString methods, all numeric conversions are implicitly called

    The Number() method performs the numerical conversion

    1. Number() applies to the objects described above

      • Conversion rules for the number method

        1. Numeric types Return result
          boolean true/1 false/0
          number Simple pass and return
          null 0
          undefined NaN
          string 1. If it contains only digits, it will only be converted to base 10 (octal is automatically zeroed)
          2. If only floating point numbers are included, they are converted to the corresponding floating point value
          3. If the value contains only valid hexadecimal numbers, convert them to decimal integers of the same size
          4. If the string is an empty string, it is converted to 0
          5. All but the above are nans

      | | object to call its transformed the valueOf method, without the valueOf method, call the toString method for translation, if the valueOf method or the toString method is not, it returns NaN |

  2. ParseInt () does not apply to objects, only strings and numbers

    • The first non-space character of the passed argument is found.
      1. If the character is not a number, NaN is returned
      2. If the string is a number, search continues until the last or non-number character is found. And then back.
    • The difference from the Number conversion string
      • Does not apply to objects, only strings and numbers
      • Number returns 0 for an empty string, and parsetInt returns NaN
      • PaserInt recognizes octal, not es5 anymore
      • ParseInt The second argument can pass a number as a base.
        • The specified argument is parsed as the specified base.
        • parsetInt(‘AF’, 16) / 175
    - parsetInt('0xAF', 16)   / 175
    Copy the code
  3. ParseFloat () does not apply to objects, only strings and numbers

    • Same as parseInt, but parseFloat has no second argument and can only recognize the data as decimal.
      • For example, parseFloat(‘0xaf’) returns 0
    • When parseFloat parses a string, the first decimal point encountered is valid, and the second one is invalid.
    • If parseFloat parses a string without a decimal point, parseFloat returns an integer.

3.3.7 type string

  • If the string type contains special literals, you need to escape them

  • Strings are immutable; once strings are created, their values cannot be changed. Changing the value simply destroys the original string and creates a new string.

  • Convert to a string. Except for null and undefined, there is no toString() method. Everything else has toString() method. The toString() method can pass an argument, return a conversion of a value to base X, and then display a string representation of the result.

  • If you do not know whether the value to be converted is null or undefined, you can use the transformation function String(XXX), which can convert any type of value to a String. This function also uses the toString method, but returns a literal if the value is null or undefined.

  • Declare the similarities and differences of a string using the way literals and objects are created

  1. Strings declared using literals are placed in the constant pool.
  2. When a method is called, it creates a temporary new String(STR) and executes the method, destroying the String after execution.
  3. You cannot add attributes or behaviors to data in a constant pool. It’s not an Object. It’s just a constant. So it has immutability.
  4. Strings created using new String are placed in heap memory.
    1. Having all the behavior of an object.

3.3.8 object type

  • An object in ECMAScript is simply a collection of data and functionality. Unordered key-value pairs. The Object type is the basis for all instances of it.

In other words, any properties and methods that the object type has also exist in more concrete objects. In other words, they are endlessly recursive.

  • Each instance of Object has the following properties and methods
    • Constructor: Holds the function used to create the current object
    • HasOwnProperty (propertyName: String): Checks if a given property is present in the instance being created, not in the prototype.
    • IsPrototypeOf (object): Used to check whether the incoming object is a prototype of the current object (????????????)
    • PropertyIsEnumerable (propertyName: String): Checks if a given property can be enumerated by the current object using a for-in statement.
    • ToString () returns the string representation of the object
    • ValueOf () Each core object overrides this method to return an appropriate value. If there is no override, the object itself is returned.
      • The valueOf method is in the form of an interface that lets custom objects customize their implementations.

3.4 the operator

JavaScript has a series of operators that operate on data values, including arithmetic operators (plus and minus), bitwise operators, relational operators, and equality operators. Because of the nature of JS, operators will perform some transformation operations in case by case discussion. Operators of complex types, on the other hand, call the valueOf() or toString() methods of the object.

3.4.1 Unary operators

  1. Increasing and decreasing

  2. One plus and one minus

    • If the data is preceded by the + / – operator. Case by case discussion

      The specific operation is shown above

  3. Bitwise operators, bitwise not, bitwise and, bitwise or, bitwise xor, etc., are related to the knowledge of computer composition courses, but not to mention.

  4. Boolean operator

    • Use!!!!! Operators can mimic the behavior of Boolean() transformation functions.

      The specific operation is shown above

  5. Logic and logic or

3.4.2 Other operators

  1. Multiplication operator

    • If it’s all numerical, do the general math

    • If one of the operands is not a value, the value that is not an operand is implicitly converted to a value by a call to Number(), and then evaluated.

  2. The division operator

    • If it’s all numerical, do the general math

    • Infinity/Infinity returns NaN

    • 0/0 returns NaN

    • If a nonzero finite number is divided by zero, the result is Infinity or -infinity, depending on the sign of the signed operand.

    • If one of the operands is not a value, the value that is not an operand is implicitly converted to a value by a call to Number(), and then evaluated

  3. Take the modulo operator

    • A divisor of 0 returns NaN

    • If one of the operands is not a value, the value that is not an operand is implicitly converted to a value by a call to Number(), and then evaluated.

  4. Addition operator

    • If one of the numbers is a string, concatenate the second operator with the first.
      • If you just add them all together
      • If one is not a string, the object’s toString() method is called to get the corresponding string. Return literals if undefined and null.
  5. Subtraction operator

    • If any of the operands are strings, booleans, null, and undefined, the Number function is now called behind the scenes to convert them to a Number. If NaN occurs, the result is NaN.
    • If one of the operands is an object, the valueOf method of the object is called to get the valueOf the object, NaN is the result if the value is NaN, and toString is called if there is no valueOf method.

3.4.3 Relational operators

The relational operators greater than, less than, less than or equal to, and greater than or equal to are used to compare two values.

Compare the rules
If both operands are numeric, a numeric comparison is performed
If both operands are strings, the character encoding values of the two strings are compared
If one operand is a value, the other operand is converted to a value, and then a numeric comparison is performed
If an operand is an object, the valueOf method of that object is called and the result is used to perform the comparison according to the previous rules. If the object does not have a valueOf method, the toString method is called and the results are compared against the previous rules
If an operand is a Boolean, it is converted to a numeric value before the comparison is performed
Any number is false compared to NaN

3.3.4 Equality operators

The recommendation is to use the congruent operator, and there is no conversion problem.

3.3.5 Ternary operators

3.3.6 Assignment operators

3.3.7 Comma operators

  • Multiple operations can be performed in a single statement using the comma operator
  1. Declare multiple variables at the same time

    var num1 = 1, num2 = 2, num3 = 3

  2. For assignment, the comma operator always returns the last item in an expression

    Var num = (5, 1, 4, 8

3.5 the statement

3.5.1 track of the for in statement

  • A for-in statement is a precise iteration statement that can be used to enumerate the enumerable properties of an object.

3.5.2 label statement

  • The label statement can add labels to code,
    • Combine the break statement with the continue statement to break out or end the loop in the future with the specified label label
label: for(var i =0; i< count; i++) {break label;
}
Copy the code

3.5.3 with statement

var qs = location.search.substring(1)
varThe hostname = location. The hostname to usewithThe statement is rewritten as followswith(location) {
    var qs = search.substring(1)
    var hostname = hostname
}
Copy the code
  • The with statement degrades performance and makes code debugging difficult. The with statement is not recommended.
  • Using the with statement in strict mode is considered a syntax error

3.5.4 function

The function encapsulates multiple statements.

  • Strict mode imposes some restrictions on functions
    • Functions cannot be named eval and arguments
    • Arguments cannot be named eval and arguments
    • Two named parameters cannot have the same name

If this happens, it will cause syntax errors and the code will not execute.

  • The function does not care how many functions are passed in, nor does it care what data type of argument is passed in, and it does not need to recognize the function signature. Ecmascript has no such rules.

  • This happens because ecMAScript parameters are internally represented as an array, and named parameters provide traversal but are not required.

  • The array of arguments can be accessed from within the function body via arguments. Arguments = array of arguments.

  • Here’s another interesting thing about arguments’ behavior:

    • An index value of Arguments maps the values of named parameters in real time.
    • That is, values modified with arguments[x] are mapped to named arguments in real time. And vice versa.
  • In strict mode, assigning arguments causes syntax errors.

  • Analog overload:

    • Overloading can be simulated by checking the type and number of arguments in the passed function and reacting differently.

4. Variable, scope, and memory issues

4.1 Values for base and reference types

  • Primitive data type values refer to simple data segments, while reference type values refer to objects that may be composed of multiple values.

  • JavaScript does not allow direct access to locations in memory, which means you cannot directly manipulate an object’s memory space. When you manipulate an object, you manipulate its reference. When you add attributes to an object, you manipulate the heap-memory data object to which the object reference points.

  • You cannot add attributes or methods to base data types. You can only add attributes or methods dynamically to reference type values.

  • Base data types and reference data types are held differently, and assignments are performed differently.

    • Basic data type assignment, direct assignment value, two variables involved in any operation is not affected.
    • A reference data type holds the reference address, which is a pointer, and changing one also changes the other.

4.2 Transferring Parameters

  • All functions in ECMAScript are passed parameters by value.

    • A primitive type is passed as if it were an assignment to a primitive type variable, and a variable referencing a type is passed as if it were an assignment referencing a data type.

    • The memory address of the value passed by the reference data type. An address is a string, but why operate on an object?

      • It may be that the address of the memory will be converted to the form of the object when the object operation is performed.
    • Prove that objects are passed by value

      function setName(obj) {
      	obj.name = "Nicholas"
          obj = new Object()
          obj.name = "Greg"
      }
      var person = new Object() setName(person) alert(person.. name)// "Nicholas"
      Copy the code
    • You can think of arguments to ecMAScript functions as local variables.

4.3 Detection Type

  • Checking whether a variable is a primitive data type uses Typeof, since reference data types using Typeof always return Object/Function.

  • Because usually we don’t want to know that a value is an object, but rather what kind of object it is. Ecmascript provides the instanceof operator for this purpose.

    Const result = variable instanceof constructor Returns true/false

  • Instanceof can only be used with objects, and always returns false for primitive types, because primitive types are not objects.

4.4 Execution Environment and Scope

The execution environment is one of the most important concepts in JavaScript. The execution environment determines the set of data that variables or functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it. The JS parser parses the execution environment into a variable object. All variables and functions in the environment are stored in this object.

The global execution environment is the most peripheral execution environment, and the object representing the execution environment varies depending on the host environment in which the ECMAScript implementation resides. Is considered a Window object in a Web browser. So all global variables and functions are mounted to the Window object. After all code in an execution environment is executed, the environment is destroyed, along with all variables and function definitions stored in it. The global execution environment is not destroyed until the application exits, such as when a web page or browser is closed.

Each environment has its own execution environment, and when the execution stream enters a function, the function’s environment is pushed onto an environment stack. After the function is executed, the stack pops up its environment. Return control to the previous execution environment. This is how flow is executed in ecMAScript programs.

When a function completes its execution, any variables or actions within the function are destroyed, its execution environment is destroyed, and its internal data is destroyed

4.4.1 Scope chain

  • When code is executed in an environment, a scope chain of variable objects is created. The scope chain looks for variables and functions needed by the execution environment. The scope chain is similar to the execution environment. When a variable or function is needed, it will find the outermost scope chain layer by layer along the scope chain. If not, an error will be thrown.
  • The inner environment can access all the outer environment through the scope chain, but the outer environment cannot access any variables and functions in the inner environment, which is linear and sequential. Each environment can search up the scope chain to query for identifiers, but no environment can search down the scope chain to enter another execution environment.
  • Arguments to a function are also treated as variables, so their access rules are the same as any other variable in the execution environment.
  • If a local variable has the same name as an external variable identifier, it can only be accessed using the external object. Identifier / [identifier].

4.4.2 Garbage Collection

How garbage collection works: Find variables that are no longer in use. It then frees the memory it occupies, which the garbage collector does periodically at regular intervals

Mainstream: Mark clearance method:

  • Variables are marked when they enter the environment and unmarked when they leave the environment.
  • When the garbage collector runs, it marks all variables stored in memory, and then it unmarks variables in the environment and those referenced by variables in the environment. Finally, the garbage collector does the cleaning. Destroy the tagged values and reclaim the memory they occupy.

Reference counting: not very common

Managed memory:

  • We can manually set an object to NULL, touch the reference to that value, and the next time the garbage collector sees that the value can be collected directly, we can develop memory management in this way.

4.5 summarize

  1. All variables exist in an execution environment (also known as a scope) that determines the lifetime of the variables and which parts of the code can access them.
    1. Execution environment is divided into global execution environment (also known as global environment) and function execution environment.
    2. Each time you enter a new execution environment, a chain of scopes is created to search for variables and functions
    3. The local environment of a function has access not only to variables in the function scope, but also to its containing (parent) environment and even to the global environment.
    4. The global environment can only access variables and functions defined in the global environment, and cannot directly access any data in the local environment
    5. The execution environment of a variable helps determine when to free memory.

5. Reference types

5.1 the Object

  • An object is an object. It’s a collection of data and functionality. An unordered collection of key-value pairs. The key must be a string. If the code is not a string, JS will also parse it as a string as a key. If it is an object or does not comply with the naming rules for variables, add [] to it.
  • Objects created by literals are not created by calling constructors.

5.2 Array

  • Objects created by literals are not created by calling constructors.

  • The length method of an array, which is not read-only, is also writable.

    var colors =[1.2.3]
    colors[2]  / / 3
    colors.length = 2
    colors[2]  // undefined
    Copy the code
  • Check arrays, although ES provides instanceof to determine the type of a variable that references the type. But here’s the problem with Instanceof:

    Assuming there is only one global execution environment, but there are multiple frames in the web page, there are actually two or more different global execution environments, and therefore two or more different versions of Array constructors. If you pass an Array from one frame to another, The array passed in has a different constructor than the array created natively in the second framework. This problem also occurs when two TAB columns communicate.

    • Solution: Array. IsArray (value) method added in ES5.
  • Array of many methods……………

5.3 the Function

  • There are two special objects inside the function
    1. Arguments (Collection of arguments)
    2. This (who calls me to whom)
  • Functions are also objects and have length and prototype attributes. Each function has non-inherited methods apply, call, and bind.

5.4 Basic Type Package Type

In addition to operating on primitive values, ES provides three special reference variables: Boolean, Number, and String. These types are similar to other reference types, but have special behavior corresponding to each primitive type. In fact, every time a primitive type value is read, an object of the corresponding primitive wrapper type is created behind the scenes, allowing us to call methods to manipulate the data.

It is recommended that you never use Boolean objects, as they can produce results that are difficult to understand.

Num.tofixed (2); num.tofixed (2); num.tofixed (2)

The property of this method is the ability to return a string representation of a numeric value in the specified decimal place, and to automatically round the decimal place

num.toExponential(2)

This method returns a string representation of a numeric value in exponential notation. The parameter passed in represents the number of decimal places in the input result

Num = 10 num. ToExponential (1) / / “1.0 e+1”

5.5 Single Built-in Objects

Built-in objects are defined as objects provided by an ES implementation that are independent of the host environment and that exist before the es program is executed.

Examples include Object, Array, String, Math, and Global

5.5.1 Global object

  • The Global object is arguably the most special object in ES. Because it doesn’t exist in any way you look at it. The global object in ES is defined in a sense as a backstop object. In other words, properties and methods that do not belong to any other object are ultimately its properties and methods. In fact, all properties and functions defined in the Global scope are properties of the Global object. IsNaN () isFinite() parseInt()…. Both are methods of the global object. Global objects exist in any environment of ES.

    • URL encoding method

      The encodeURI() and encodeURIComponent() methods of the Global object encode urIs. So it can be sent to the browser.

      Valid URIs cannot contain illegal characters such as Spaces, and these two URI encodings can encode URIs.

    • Why is that?

    • Because if our access address is Chinese, or with Spaces and other illegal characters, we need to use URI encoding and then send to the browser for recognition.

    • EncodeURI does not encode special characters of the URI itself, such as http://www.baidu.com?wd= Spelling duo

      • The: // type is not encoded
    • EncodeURIComponent encodes all illegal characters.

    • Generally we use encodeURI to parse the entire URI

    • Use encodeURIComponent to parse the uri query string

    • DecodeURI () and decodeURIComponent() are used to decode, but the former cannot decode %23 because %23 is #

  • If the js host environment is a browser, the window object acts as a proxy for the Global object.

5.5.1 Math object

  • There are two built-in objects in scope before any code executes: Global and Math.