The following content is a review record of personal study, mainly excerpts from some network materials. As well as some of their own summary, there may be some mistakes, if found, welcome to correct!!

The learning content mainly comes to: github.com/stephentian…

Execute function expressions now (IIFE)

1. Basic Concepts

  • IIFE: Imdiately Invoked Function Express (Execute Function expression immediately) LLC.
/* The output 'Hello World' */ will be automatically executed later; (function (str) {
  console.log(str)
})('Hello World')
Copy the code

Second, the meaning of parentheses

1. Wrap parentheses around function

  • The parentheses are mainly for the purpose of separatingfunction(){}Convert to an expression
  • The parentheses are also available~,+Instead of
  • The parentheses cannot be removed because they arefunction(){}It’s not an expression

e.g.

~function () {
  console.log(123)
}()
Copy the code
+function () {
  console.log(123)
}()
Copy the code

2. Second parenthesis

  • The second parenthesis is mainly to enable the expression to be executed

3. Meaning of parameters

; (function (str) {
  console.log(str)
})('Hello World')
Copy the code

1. The argument

  • The real participator in the function corresponds one to one as STR in the example above would be assigned toHello World

2. Parameter

  • Common parameters
    • That is the argument passed in the second parenthesis
  • Special parameterundefined
    • To prevent undefined from being changed, the undefined value can be changed in IE6 and other older browsers
    • Compression code can compress undefined

The module

First, several writing methods of modules

1. Original writing

  • A module is a set of methods that implement a specific function
  • Simply put the different functions (and the variables that record the state) together as a module

e.g.

function m1 () {
  /* code */
}

function m2 () {
  /* code */
}
Copy the code
  • Disadvantages:
    • Contaminate global variables
    • There is no direct relationship between module members

2. Object writing

  • Put all module members into one object

e.g.

var module = {
  _count: 0.m1: function () {
    /* code */
  },
  m2: function () {
    /* code */}}Copy the code
  • Disadvantages:
    • Exposed module members, the internal state can be modified directly by the department

3. Write the function immediately

  • With the immediate execution function, the module members to be exposed are returned and the rest are not returned, protecting the internal members

e.g.

var module = (function () {
  var _count: 0
  var m1 = function () {
    /* code */
  }
  var m2 = function () {
    /* code */
  }
  return {
    m1: m1,
    m2: m2
  }
})()
Copy the code

4. Zoom mode

  • Each time you add a module, you declare the namespace so that you don’t have to worry about the order in which the code is executed
  • Points to pay attention to
    • Check whether the namespace is initialized each time you mount a function module to the namespace. If no, initialize the namespace
    • After the function hangs, the new namespace should be returned to update the namespace

e.g.

var module = (function (module) {
  if (typeof module= = ='undefined') {
    module= {}}module.m1 = function () {
    console.log('m1 function')}return module}) (module)

var module = (function (module) {
  if (typeof module= = ='undefined') {
    module= {}}module.m2 = function () {
    console.log('m2 function')}return module}) (module)
Copy the code

5. Wide zoom mode

  • Used in arguments||To take advantage ofwindow.module||(window.module = {})If the namespace module in the window is instantiated, it is passed directly to module; otherwise, subsequent expressions are executed(window.module={})And returns a reference to window.module

e.g.

; (function (module) {
  if (typeof module= = ='undefined') {
    module= {}}module.m2 = function () {
    console.log('m2 function')}return module}) (window.module || (window.module = {}))
Copy the code
  • Advantages: Can be divided into multiple files for loading, regardless of the file loading order (because every time the module adds a function module, it checks whether the corresponding namespace is created in the window, if so, it will directly use the corresponding namespace)

Module writing attention content

  • It is best to use immediate function expressions before;To end the previous code segment, otherwise there will be a merge problem; For example, there is a sentence in file Aconsole.log(1); Whereas the b file is an immediate function expression without a semicolon, the merged code will become
console.log(1) (function () {
  /* code */}) ()Copy the code

This will be executed as follows

console.log(1) (function () {
  /* code */}) ()Copy the code

The code will report an error

Normalization of modules

1, CommonJS specification (synchronous loading module)

  • userequireMethods toSynchronous loading(When the require statement is encountered, the corresponding module file will be loaded in, and the subsequent code execution needs to wait for the module to complete loading before execution.) Other modules; throughexportsormodule.exportsTo export the interfaces to be exposed

e.g.

/* Module import */
require('Koa')
require('./module.js')

/* Module export */
exports.m1 = function () {}
module.exports = someValue
Copy the code
  • advantages
    • Easy to use
    • Server-side modules are easy to reuse
  • disadvantages
    • Synchronous loading is not suitable for the browser environment because the loading speed is affected by the network. Asynchronous loading of browser resources is affected
    • You cannot load multiple modules without blocking

Two, AMD (asynchronous loading module)

  • Using asynchronous loading
  • All statements that depend on a module are placed in a callback function and are not executed until the module has loaded

e.g.

// Define the module
define('module'['dep1'.'dep2'].function (d1, d2) {/* code */});

// Load the module
require(["module".".. /app"].function(module,app){/* code */}
Copy the code
  • advantages
    • Suitable for loading modules in a browser (asynchronous loading)
    • Multiple modules can be loaded in parallel
  • disadvantages
    • Increased development costs, code reading and writing difficulties, block definition statements
    • Does not accord with the general modular development way of thinking
  • Tips: The specification for implementing AMD is require.js

CMD (asynchronous loading module)

  • A module is a file in CMD

  • The definition module uses the global function define to accept a factory argument, which can be function \ object \ string

  • When factory is a function, it takes three arguments

    • Require: function that receives a module as its only argument and is used to get the interface of another module
    • Exports: objects used to provide interfaces to the outside world
    • Module: object that stores properties and methods associated with the current module
  • advantages

    • Dependencies are close and execution is delayed
    • Easy to run in Node.js
  • disadvantages

    • Rely on SPM packaging, module loading logic is biased

Fourth, the UMD

  • A mashup of AMD and CommonJS
  • Exports that support Node.js exist, CommonJS specification is used, otherwise AMD mode is supported (define exists), AMD specification is used

ES6 specification

  • In the language standard level to achieve module functions, simple implementation, can replace CommonJS and AMD specifications, become the browser server universal solution
  • ES6 module specification design idea: static as much as possible, determine module dependencies at compile time, and input/output variables (both CommonJS and AMD modules can only determine this at run time)

e.g.

/ / import
import "app.js"
import React from "react"

/ / export
export function app(){/* code */}
export const count=0
export default.Copy the code
  • advantages
    • Easy to perform static analysis
    • ES standard for the future
  • disadvantages
    • The standard is not yet implemented on the native browser side
    • New command words that are only supported by new versions of Node.js

CommonJS vs. ES6

  • CommonJS userequire/exports; Use ES6import/export

CommonJS

  • The primitive data types in a module are copied when imported, and another module can reassign the exported primitive values without affecting the use of other modules
  • Complex data types in modules are shallowly copied when they are introduced. Objects referenced by both modules point to the same memory space, and changes in the values of one module will affect the execution of the other
  • Require executes the code for a module file when it loads the module. Repeated introductions do not result in repeated execution; values are fetched directly from the cache

ES6

  • Values in ES6 modules are dynamic read-only references
  • The imported value of import generates a dynamic read-only reference. When the module encounters an import, it generates a dynamic read-only reference to the imported variable. The value can be evaluated based on this reference and cannot be modified. When the original value of the introduced variable changes, the loaded variable will also change. The above variables hold for both primitive and complex data types

Pay attention to the point

  • Require and exports are required no matter what specification is used because import/export is written through require/exports