JS programming

ECMAScript(ES)

The JS language itself

Generally regarded as the standard specification of JS

JS is actually an extension of ECMAScript

ECMAScript provides only the most basic syntax.

JS

  • Web environment

    • ECMAScript

    • WebApis

      • BOM
      • DOM
  • The Node environment

    • ECMAScript

    • NodeApis

      • fs
      • net
      • etc.

ES2015

  • Also called ES6

    • Especially ECMAScript2015.

    • Used broadly to refer to all new standards.

      • “Async and await with ES6”
  • This is a big change compared to ES5.1

  • Since then, the standard naming rules have changed.

  • New features

    • Let and block-level scope

      • Scope: The scope within which a member can act.

      • Before that, there are two scopes

        • Global scope
        • Function scope
      • Added block-level scope

        • The range enclosed in curly braces
        • Variables defined by block-level scopes are not accessible externally.
    • const

      • Declare measurements or constants

      • A read-only feature is added to let.

        • Variables cannot be modified once declared
    • An array of deconstruction

      • Const array = [‘ time ‘,’ 3 ‘]

const [ sjz, spl ] = array

- object destruct - const obj = {name: 'time solution ', age: 31} - const {name} = obj - template string literal - support multi-line input - support for inserting JS variables or expressions - instance:Copy the code

Const name = ‘console.log’ (I’m ${name})

- Template string tag function - String extension method - startswith-endswith-includes - Parameter default - Remaining parameters - Expand array - console.log(... [' time solution ',' three beautiful ']) - arrow function - const fun = n => n+1 - arrow function and this - arrow function does not change this pointing. - Object literal enhancement - const bar = 515Copy the code

Const obj = {foo: 666, bar, add () {return this.bar + 1}, [math.random ()]: ‘Calculate attribute name’}

- Object extension method - object. assign - Can copy the attributes of multiple source objects to a target Object. - Object.is - +0 === -0 : trueCopy the code

Object.is(+0,-0) : false – NaN === NaN : false Object.is(NaN,NaN) : true

- Proxy - new Proxy(targetObj, HandlerObj) - vs. object.defineProperty () - defineProperty can only monitor reads and writes of attributes - Proxy can monitor more Object operations - delete - method calls in objects - etc. - Proxy regulates reading and writing of objects in a non-intrusive way. - Reflect - A unified object manipulation API. - Reflect encapsulates a set of low-level operations on objects. The -reflect member method is the default implementation of Proxy handling objects. - A unified SET of apis for manipulating objects - Promise - a better asynchronous programming solution - solves the problem of deeply nested callback functions in traditional asynchronous programming. - class Class - Instance method - Static method - ES2015 Added static keyword to add static members. - method front ➕static - class inheritance - extends - use super to indicate the parent class instance - set-add - can chain call - delete-clear-has-map - set-get-has - Delete-clear-symbol - a new primitive data type - represents a unique value - Symbol() === Symbol() : False - can be used to truly implement private object members - the main function is to add unique property names to the object. - Symbol.for('sjz') === Symbol('sjz') : true - Symbol.for(true) === Symbol.for('true') : True - built-in constants - Symbol. The iterator - Symbol. HasInstance - Symbol. ToStringTag - through Object. GetOwnPropertySymbols (obj) Symbol attributes - for... Of loop - uniform way to iterate over all data structures - Loop body can terminate loop directly with break - Current support - Array - Set - Map - Iterated object is not supported - iterable interface - More and more structured data types can be represented in ES. - To provide uniform traversal for various data structures. - Yes, you can use for... The premise of of - iterable - must have a symbol. iterator property method inside that returns iterator - an iterator object that contains the next method - an IterationResult object that returns value and done. - Iterator mode - Generator - Avoid deep nesting of callbacks in asynchronous programming - Provide a better asynchronous programming solution - use yield keywords in function bodies - lazy execution - apply - Generator - Implement iterator methods - function * Definition - ES Modules - Language level modularity standardsCopy the code

ES2016

  • Includes method of an array instance object

    • Traditionally, indexOf is used to find the presence of an element in an array, returning -1 if it does not exist. The disadvantage is that NaN cannot be found.
    • You can look for NaN.
  • Exponential operator

    • 2 * * 10

ES2017

  • Object.values

  • Object.entries

  • Object.getOwnPropertyDescriptors

  • String.prototype

    • padStart
    • padEnd
  • Add trailing commas to function arguments

  • async/await

The TypeScript language

Solve the problem of JS type system

You can greatly improve the reliability of your code

JS own type system problems

Type safety

  • Strongly typed

    • A language-level constraint that a function’s argument type must be the same as its parameter type.
    • There are stronger type constraints.
    • Arbitrary implicit type conversions are not allowed.
    • The grammatical level of the language is restricted
  • Weak type

    • The language level does not restrict the types of arguments.
    • There are few constraints.
    • Allows arbitrary data implicit type conversions.

Type checking

  • The static type

    • When a variable is declared, its type is unambiguous.
    • Once a variable has been declared, its type cannot be changed.
  • Dynamic type

    • Run time is the time to specify variable types
    • And variable types can change at any time.
    • It can also be understood that a variable has no type.

And the values that are stored in variables are typed.

JS type system features

  • Weak type

    • There is a problem

      • Some types of exceptions need to wait until run time to be found.
      • An undefined type can cause function functionality to change.
      • Causes incorrect use of the object indexer.
    • Strong type dominance

      • You can eliminate most type exception problems before running.
      • Mistakes are exposed earlier
      • The code is smarter, the code is more accurate.
      • Refactoring is more robust.
      • Reduce unnecessary type judgments.
  • Dynamic type

  • Missing the reliability of the type system.

  • JS does not compile

Flow

  • JS type checker

  • It was launched by Facebook in 2014.

  • Declare data types using type annotations

  • It is not required to add type annotations to all variables.

  • Compared to Typescript, Flow is just a gadget.

  • Installation: yarn add flow-bin

  • Use: // @flow

  • Initialize the flow configuration file: yarn Flow init

  • Remove type annotations by compilation

    • yarn add flow-remove-types –dev

      • yarn flow-remove-types src -d dist
    • yarn add @babel/core @babel/cli @babel/preset-flow –dev

      • Add babelrc.

        • Content: {

    “presets”: [“@babel/preset-flow”]

}

	- yarn babel src -d dist
Copy the code
  • Flow development tool plug-in

    • VSCode extensions: Flow Language Support

      • Type errors are detected only after saving.
  • Type inference

  • Type annotations

    • Function parameters

    • Function return value

    • variable

    • type

      • The original type

        • :string

        • :number

          • NaN
          • Infinity
        • :boolean

          • false
          • true
        • :null

          • null
        • :void

          • undefined
        • :symbol

          • new Symbol()
      • T: number | string | boolean | null | void | symbol

      • An array type

        • :Array

        • :T[]

        • :[T, T, …]

          • tuples
      • Object type

        • :{ key? : T, key2: T, … ,keyn: T}
        • :{ [T]: T }
      • Function types

        • : (T, T, … , T) => T
      • Special type

        • Literal type

          • : ‘foo’
        • Join literal types

          • :’foo’ | ‘bar’ | ‘sjz’
        • The joint type

          • : T | T
        • Type Indicates the type of the association

          • type StringOrNumber = string | number
          • Use: : StringOrNumber
        • Maybe the type

          • 😕 T
        • Mixed with Any

          • : mixed

            • A combined type of all types
            • Strongly typed
            • Specify the specific type before using it.
            • Explicit via Typeof.
          • : any

            • Weak type
            • To be compatible with some of the previous historical code.
  • Runtime environment API

    • Built-in objects

      • Browser environment API
      • The Node environment API

TypeScript

  • A superset of JS

    • JS
    • The type system
    • ES6+
  • It will eventually compile to JS

  • Any TYPE of JS runtime environment is supported

  • The function is more powerful, the ecology is more sound, more perfect.

  • Use the sample

    • Angular
    • Vue. Js 3.0
  • Second language in front-end understanding.

  • disadvantages

    • The language itself adds a lot of concepts.
    • TypeScript adds some cost early in the project.
  • advantages

    • TypeScript is ☞ progressive
  • Quick learning

    • Initialize package.json file: yarn init –yes

    • Install: yarn add typescript –dev

    • Create a new.ts extension file to write code.

    • Compile: yarn TSC filename.ts

      • Check for type usage exceptions in your code.
      • Remove some extension syntax from type annotations
      • New feature of automatic conversion ES.
  • The configuration file

    • Generate: yarn TSC –init
    • The configuration does not take effect until the entire project is compiled
  • Type annotations

    • The original type

      • : string

        • Unlike Flow, null is allowed in non-strict mode
      • : number

        • Unlike Flow, null is allowed in non-strict mode
      • : boolean

        • Unlike Flow, null is allowed in non-strict mode
        • true
        • false
      • : void

        • null
        • undefined
      • : null

      • : undefined

      • : symbol

        • new Symbol()
    • Standard library declaration

      • The library is the declaration of the built-in object.
    • Chinese error message

      • Settings: Preferences ⥤ Settings⥤ Search for typescript locale⥤ select zh-cn
    • Scope problem

      • Solution 1: Execute the function immediately
      • Export {}
    • The Object type

      • It’s not just a generic object type.

      • A generic term for all non-primitive types.

        • object
        • An array of
        • function
      • : object

      • : { key: T, key2: T,… , keyn: T }

        • There can be no more or fewer object attributes.
        • Not recommended. Interface definition is recommended
    • An array type

      • :Array
      • :T[]
    • A tuple type

      • :[T, T, …]
    • Enumerated type

      • Statement: enum EnumName {

    enum1 = 1, enum2 = 2

} – use: enumname.enum1 – will invade runtime code. – Constant enumeration

- Definition: const enum EnumName {enum1: 1, enum2Copy the code

} – Use: enumname.enum1

- Function type - Function declaration - Example:Copy the code

Function func1 (a: T =’T type value ‘, b? : T,… Rest: T[]): T {return T type value ‘}

- Function expression - : (a: T, b: T... , n:T) ⥤ T - Arbitrary type - : any - implicit type inference - Example: let age = 31 - Any - type assertion - as T - <T> - easily confused with JSX syntax when the type cannot be inferred. - interface - used to specify the structure of the object - definition:Copy the code

interface IName { field1: T field2: T selectableField? : T readonly readOnlyField: T [dynamicField: T]: T }

- Class - Describes the abstract characteristics of a class of things - used to describe the abstract members of a class of objects - ES6 before, function + prototype simulation implementation classes. - ES6 starts with class-typescript classes that enhance class-related syntax. - definition:Copy the code

Class ClassName {field:T = ‘initial value’ field2: T constructor (field:T, field2: T) {this.field2 = field2}} – Access modifier

- definition:Copy the code

Class ClassName {protected readonly field:T = ‘constructor’ private privateField2: T constructor (field:T, field2: T) { this.privateField2 = field2 } static staticMethod (field1: T, field2: T) {return new ClassName(field1, field2)}} – default public-private-protected-static

Implements an interface through implements -- Abstract classes -- can contain specific implementations -- cannot be instantiated -- defines: Abstract class - can only be inherited through the extends keyword - Abstract methods can be defined using the abstract keyword in the class body - no method body - only method signatures - generics - No type is specified when defining functions, interfaces, or classes. We wait until we use them to specify specific types of characteristics. - Function: Reuse code to a great extent. - the sample:Copy the code

function genericsFn (arg1: T, arg2: T): T { return arg1 + arg2 }

- Type declaration - Mainly for third-party modules - Example: lodash-yarn add @types/lodash -- dev-declare function camelCase(INPUT: string): The string -.d.ts file is the type declaration file. - Some modules have their own type declaration modules, which need not be installed or declared separately.Copy the code

JS performance optimization

JS memory Management

  • JS memory management is automatic

  • memory

    • It consists of read/write units and represents a piece of operable space
  • management

    • Artificial to operate the application, use and release of a space.
    • Management process: Apply » Use » Release.
  • Developers actively apply for space, use space, release space.

  • Let obj = {}

  • Use space: obj.name = ‘time solution’

  • Free space: obj = null

Garbage collection in JS

  • Garbage collection in JS is to find garbage objects and then release and recycle them.

  • Garbage in JS

    • Objects become garbage when they are no longer referenced
    • Objects become garbage when they cannot be accessed from the root
  • Reachable objects in JS

    • Accessible objects are reachable objects (references, scope chains)
    • The criterion of reachability is whether it can be found from the root.
    • Roots in JS can be understood as global variable objects.

GC

  • GC is short for garbage collection mechanism

  • The GC finds garbage in memory and frees and reclaims memory space

  • Garbage in GC

    • Objects that are no longer needed in a program
    • An object in a program that can no longer be accessed
  • GC algorithm

    • What is the GC algorithm?

      • GC is a mechanism where the garbage collector does the specific work
      • The job is to find garbage, free space, reclaim space
      • An algorithm is a set of rules that lookup and recycle follow at work.
    • Reference counting

      • Realize the principle of

        • Set the number of references and check whether the current number of references is 0.
        • Reference counter
        • Modify the reference number when the reference relationship changes.
        • If the reference number is 0, it is immediately reclaimed.
      • advantages

        • Recycle rubbish as soon as it is found
        • Minimize program pauses
      • disadvantages

        • Object referenced by loop cannot be recycled
        • High resource consumption
    • Mark clear

      • Realize the principle of

        • Core idea: mark and clear two stages to complete.
        • Traversing all objects marks all reachable objects as active.
        • Iterate over all objects to remove unmarked objects and remove the original tags.
        • Reclaim the corresponding memory space
      • advantages

        • Objects referenced by a loop can be recycled
      • disadvantages

        • It is easy to generate fragmented space and waste space.
        • Garbage objects are not collected immediately.
    • Tag to sort out

      • Realize the principle of

        • Tag cleanup can be seen as an enhancement to tag cleanup.
        • The operation of the tag phase is the same as that of tag clearing.
        • The cleanup phase starts with a cleanup, moving the object.
      • advantages

        • Reduce the space for fragmentation
      • disadvantages

        • Garbage objects are not collected immediately

V8

  • V8 is a mainstream JS execution engine

  • V8 uses just-in-time compilation

  • V8 memory limit (1.5 GB for 64-bit OS and 800 MB for 32-bit OS)

  • V8 garbage collection strategy

    • The idea of generation recycling is adopted
  • V8 memory space

    • New Generation Object Storage

      • V8 memory space is split in two
      • Small space for storing new generation objects (32 MB for 64-bit OS and 32 MB for 32-bit OS)
      • Cenozoic refers to objects that have a short life span
    • Old generation object storage

      • Old age objects are stored in the old age area on the right.
      • Memory limit: 1.4 GB for 64-bit OS and 700 MB for 32-bit OS.
      • An old age object is an object that lives for a long time.
  • V8 commonly used GC algorithm

    • Generational recycling

      • Different algorithms are used for different objects

      • Memory is divided into new generation, old age

      • Realize the principle of

        • The new generation

          • The recycling process adopts replication algorithm + label finishing.

          • The new generation of memory is divided into two equal size Spaces, namely From and To.

          • The used space is From, and the free space is To.

          • Live objects are stored in the From space.

          • The live object is copied To the To space after the tag is collated.

          • The space exchanged between From and To is released.

          • Recovery Details

            • Promotions may occur during copying

              • New generation that survives a GC round needs to be promoted.
              • To space usage is over 25%
            • Promotion is the movement of the new generation to the old generation.

        • The old s

          • It mainly adopts the algorithm of mark clearing, mark finishing and increment mark.
          • Garbage space is first collected using a tag sweep.
          • Spatial optimization was carried out by label finishing.
          • Incremental marking is used for efficiency optimization.
        • Comparison of new generation and old age waste recycling details

          • New generation of garbage recycling space time.
          • Old-age area garbage collection is not suitable for replication algorithms
    • Space to copy

    • Mark clear

    • Tag to enhance

    • Mark the incremental

      • Program execution alternates with garbage collection.

The Performance tools

  • Why use Performance?

    • The purpose of GC is to achieve a virtuous cycle of memory space.
    • The cornerstone of this virtuous cycle is the proper use of memory.
    • Keeping an eye on memory changes makes sense.
    • Performance Provides multiple monitoring modes.
    • Monitor memory time by Performance.
  • Memory problems

    • Pages load lazily or pause frequently.
    • The page continues to have poor performance.
    • Page performance deteriorates over time.
  • Several ways to monitor memory

    • Criteria for defining memory leaks

      • Memory leak: memory usage lasts height.
      • Memory bloat: Performance issues on most devices.
      • Frequent garbage collection: Analyzed by memory variation graph.
    • Browser task manager

      • Shift+Esc brings up the task Manager

      • Observe the two column values

        • Native DOM memory
        • Javascript memory
    • Timeline Records the Timeline diagram

    • Heap snapshot looks for detached DOM

      • What is DOM separation

        • Interface elements live in the DOM tree.
        • DOM node when garbage object.
        • Separate state DOM nodes.
    • Determine if there is frequent garbage collection

      • Why frequent garbage collection

        • The application is stopped while the GC is working
        • Frequent and long GC can lead to application suspension.
        • The user awareness application is stuck.
      • Frequent ups and downs in Timeline.

      • Frequent data increases and decreases in task manager.

Introduction to code optimization

  • How to accurately test JS performance?

    • Essentially, a large number of execution samples are collected for mathematical statistics and analysis.
    • This is done using JsPerf based benchmark.js
  • Be careful with global variables

    • Why should it be used sparingly?

      • Global variables are defined in the global context and are at the top of any scope chain.
      • The global execution context remains in the context execution stack until the program exits.
      • The presence of a variable with the same name in a local scope obscures or contaminates the whole world.
  • Caching global variables

    • Global variables that cannot be avoided in use are cached locally
  • Add by prototype

    • Methods needed to add an instance object to a prototype object.
  • Avoid closure traps

    • Closure features

      • The outside has a reference to the inside
      • Access data from the inner scope in the outer scope.
      • Closures are a powerful syntax
      • Closures are prone to memory leaks when used improperly.
      • Don’t close for closure’s sake.
  • Avoid using attribute access methods

    • Object oriented in JS

      • JS does not require access to properties, all properties are externally visible.
      • Using attribute access methods only adds another layer of redefinition without access control.
  • For loop optimization

    • Cache the loop array length before using it
  • Choose the optimal loop method

    • Choose an Array of forEach
  • Document fragmentation optimization node added

    • The addition of nodes inevitably involves backflow and redraw.
  • Clone optimized node operation

  • Replace Object directly

  • JSBench

    • JS execution in the stack

      • Heap: function declarations, objects, arrays
      • Stack: Creates execution contexts, literals, local variables
    • Reduce the level of judgment

      • Determine invalid conditions in advance and return directly if they are invalid
    • Reduce the scope chain lookup level

    • Reduce the number of data reads

    • Literals and constructors

    • Reduce circulatory body activity

    • Reduce the number of declarations and statements

    • Use event binding

      • Using event delegate

        • ul vs li