navigation

[react] Hooks

[Package 01- Design Pattern] Design Principles and Factory Pattern (Simple Abstract method) Adapter pattern Decorator pattern [Package 02- Design Pattern] Command pattern Share pattern Composition pattern Proxy pattern

[React from Zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose React +egg+nginx+mysql [react from zero practice 05- background

AST Abstract syntax tree [source-webPack02-pre knowledge] Tapable [source-webpack03] Hand-written Webpack-compiler simple compilation process [source] Redux React-redux01 [source] axios [source] koa [source] vuex [source-vue01] data Responsive and initialized render [source-vue02] computed responsive – initialized, access, Update process [source-vue03] Watch listener – Initialize and update [source-vue04] vue. set and vm.$set [source-vue05] vue.extend

Vue.nextTick and vm.$nextTick

[source code -react01] ReactDOM. Render01 [source code -react02] handwritten hook scheduling -useState implementation

[Deployment 01] Nginx [Deployment 02] Docker Deployment Vue Project [Deployment 03] Gitlab-CI

Data Structures and Algorithms 01 binary lookup and sorting

[Delve 01] Execution context [Delve 02] Prototype chain [Delve 03] Inheritance [Delve 04] event loops [Delve 05] Currization partial functions Function memory [Delve 06] Implicit conversions and operators [Delve 07] Browser caching mechanism (HTTP caching mechanism) [Delve 08] front-end security [In Depth 09] Deep copy [in depth 10] Debounce Throttle [in depth 11] Front-end routing [in depth 12] Front-end modularization [in depth 13] Observer mode Publish subscribe mode Bidirectional data binding [in depth 14] Canvas [in depth 15] webSocket [in-Depth 16] Webpack [in-Depth 17] HTTP and HTTPS [in-Depth 18] CSS-Interview [in-Depth 19] Handwritten Promise [In-depth 20] Handwritten Functions [In-depth 21] Data Structures and Algorithms – Binary Lookup and Sorting [In-depth 22] Js and V8 garbage collection mechanisms js design patterns – Proxies, policies, singletons – Fiber – Typescript – Drag

[Front-End learning java02-SpringBoot actual] environment configuration and HelloWorld service [front-end learning java02-SpringBoot actual] mybatis + mysql implementation song add, delete, change to check [front-end learning java03-SpringBoot actual] Lombok, log, Deployment [front-end learning Java04 -SpringBoot actual practice] static resources + interceptor + front and back end file upload [front-end learning JAVa05 -SpringBoot actual practice] common notes + Redis to achieve statistical function [front-end learning Java06 -SpringBoot actual practice] injection + Swagger2 3.0 + Unit test JUnit5 [Front-End learning Java07 -SpringBoot practice] IOC scanner + transaction + Jackson [front-end learning Java08 -SpringBoot practice summary 1-7] stage summary [front-end learning Java09 -SpringBoot actual combat] multi-module configuration + Mybatis-plus + single multi-module package deployment [front-end learning Java10 -SpringBoot actual combat] Bean assignment conversion + parameter verification + global exception processing [front-end learning Java11-SpringSecurity] configuration + Memory + database = three ways to implement RBAC [front-end learning Java12-SpringSecurity] JWT [front-end learning Java13-SpringCloud] Eureka + RestTemplate + Zuul + Ribbon

Review Note-01 Review Note-02 Review Note-03 Review Note-04

Front knowledge

Some words

// MutationObserver algorithm migration Migration Repository setup Set tissue induction descriptor immutable to induction descriptor immutableCopy the code

(a) the difference between scope and execution context

  • (Scope) (scope chain) (execution context) (Execution context stack)
  • Summarize the differences between scope and execution context !!!!!!!!!!!!!!!
    • Time of formation
      • Function scope: determined at function definition time
      • Function execution context object: created when a function is called and the function body is not executed
    • Static and dynamic
      • Function scope: is static, defined at function definition, and does not change
      • Function execution context object: is dynamic, created when the function is called, and released after the function is executed
    • contact
      • (Execution context object) subordinate to (scope)
      • (Global execution context object) belongs to (global scope)
      • (function execution context object) belongs to (function scope)

Scope (1.0)

  • The concept of scope
    • Refers to the range in which (variables and functions) exist
  • The scope ofThe main role
    • Segregation variable, i.e.,Different scopeUnder theThe same variableDon’t conflict
  • Classification of scopes
    • Global scope– Variables persist throughout the program
    • Function scope– Variables exist only inside functions,Function scope is formed when a function is created
    • Block-level scope
  • The scope of the function itself
    • The function itself is also a value and has its own scope
    • The scope of a function, like a variable, is the scope in which it is declared, independent of the scope in which it is run
    • The scope in which a function executes is the scope in which it was defined, not the scope in which it was invoked
    • (function body) (inner) the declared function, (scope of the inner function) bound inside the outer function
  • The characteristics of
    • The global variableVariables declared outside a function are global variables and can be read inside a function (only one layer of functions).
    • A local variable:
      • A variable inside a function cannot be read from outside the function
      • Overrides (global variables) in (scope)
      • For var commands, local variables can only be declared in a function, in other blocks, are always global variables

(1.1) Scope chain – consists of nested scopes

(1.2) Execution context

  • EC: execution context
  • See juejin. Cn/post / 684490…
  • classification
    • Global execution context
    • Function execution context
    • eval
  • Global execution context
    • inBefore executing the global codeTo (windowDetermined to beGlobal execution context )
    • To process (global data).
      • The global variable
        • Global variable defined by var (variable promotion) : assign undefined and add the property of window
      • Global function
        • Global functions declared by function (function promotion) : assign fun to function, add window method
      • this
        • Assign this to Widnow
    • Start executing global code
      console.log(`a`, a, window.a);
      console.log(`b`, b, window.b);
      console.log(`this`, this)
    
      var a = 10;
      function b() {
        return 20;
      }
      // a undefined undefined
      // b b() { return 20; } b() { return 20; }
      // this window
    Copy the code
  • Function execution context
    • In the (Call a function), (Before the function body is ready to execute), (createCorresponding to (Function execution context object )
      • Note the object global execution context and the function execution context
      • Global: Use Window as a global execution context object before executing global code ->Window was there before
      • Function: Create a function execution context object when a function is called and before the function body is executed ->The newly created
    • Local data is preprocessed
      • parameter
        • Declare a parameter variable, assign it as an argument, and add attributes to the execution context object of the function
      • Argument object
        • Argument object and add attributes to the execution context object for the function
      • A local variable
        • Promote the variable, declare the variable, assign it a value of undefined, and add attributes to the execution context object of the function
      • function
        • The function is promoted, the entire function is promoted to the header, and attributes are added to the execution context object for the function
      • this
        • Assign this to the object that calls this function
  • Perform context summary
    • Execution context is divided into: global execution context, function execution context, eval
    • The essence of an execution context :(execution context) is an (object)
    • Global execution context
      • Treat window as a global execution context object before executing global code
      • Global variable promotion, global function promotion, this assignment
    • Function execution context: Creates a function execution context object when a function is called and before the function body is executed
      • A function execution context is created when the function is called and before the function body is executed
      • Parameter assignment, arguments object assignment, local variable promotion, local function promotion, this assignment
      • Each time a function is called, a function execution context is generated

(1.3) Execute context stack

  • define
    • In the (Global code before execution), the js engine will create a (The stack) to store and manage all (Execution context object )
    • Push: After the global execution context window is identified, it is added to the stack
    • Push: After the execution context of a function is created, it is added to the stack
    • Push out: After the current function completes execution, the execution context object at the top of the stack is pushed out
    • Finally: When all the code has been executed, only the global context objects are left on the stack
  • The characteristics of the stack
    • Last in, first out, same entrance and exit
  • Characteristics of queues
    • First in, first out, different entrances and exits

console.log(`a`, a); var a = 1; fn(a); function fn(a) { if (a === 4) return; The console. The log (" before ", a); fn(a + 1); The console. The log (" after ", a); } // undefined first 1, first 2, first 3, last 3, last 2, last 1Copy the code

(1.4) The relationship between arrow function this and the upper scope

  • This in the arrow function refers to the scope in which the arrow function is defined.
  • So what is scope
    • Scope:
      • Refers to the scope in which a variable exists, divided into global scope, function scope, block level scope
      • Function scope: generated when a function is defined and does not change
    • Execution context
      • An execution context is really just an object
      • There are global execution context, function execution context, eval
      • Function execution context object: generated when a function is called and before the function body is executed
This in the arrow function refers to this ------- // 1 var a = 100; const obj = { a: 1, b: function () { console.log(this.a); }, c: () => console.log(this.a), }; obj.b(); // this refers to the object on which the function was called, obj.c(); // this is in the upper scope of the arrow function. Obj is in the upper scope of the block level scope. Obj is in the upper scope of the block level scope. Var a= {name: "a ", sayHello: function () {var s = () => console.log(this.name); return s; }}; var sayHello = A.sayHello(); SayHello (); sayHello(); sayHello(); The arrow function s is defined in the same scope as sayHello. Upper scope: block level scope A, this refers to A, a.name = 'A'Copy the code

(2) The composition of the browser

  • The browser (core) has two parts
    • ( Rendering engine )
    • ( Javascript engineAlso calledJavascript parser )

(2.1) Rendering engine

  • The main role of the rendering engine
    • Render (web page code) into (a flat document that the user perceives visually)
    • Different browsers have different rendering engines
  • The rendering engine processes the code in six main stages
    • parseHtml->parseStylesheet->evaluateScript->layout->paint->composite
    • See juejin. Cn/post / 698357…

(2.2) javascript engine

  • The javascript engine reads the javascript code in the web page, processes it and runs it
  • The browser handles the javascript code as follows
    • Lexical analysis: Read the code and proceedLexical analysisThat will becodeBroken down intoTokens
    • Syntax analysis:Lemmas tokenforParsingAnd organize the code into"Syntax Tree"
    • The bytecode: Use translator to convert code toBytecode
    • Machine code: To use the bytecode Interpreter, willThe bytecodetoMachine code
  • conclusion
    • Code -> token -> syntaxTree -> bytecode -> machine code

In react-ElementDiff, index is used as key.

  • Case 1
    • Render three inputs, entering 0, 1, 2 in each of the three inputs
    • Delete the first input
      • key=index
        • Delete the index of the first input =0, and the index of the remaining two inputs will be 0 and 1 respectively
        • The diff comparison
          • Since the previous (key=012), (now key=01)
          • So React argues that the first two elements are unchanged, but the third element is missing
          • So the action is to simply delete the third element, leaving the two input fields with values of 0, 1 and the expectation of 1, 2
          • Fall short of expectations
      • key=id
        • Delete the first input with key=0, and the remaining two input render keys are 1 and 2
        • The diff comparison
          • Since (key=012), (now key=12)
          • So React thinks it deleted the first element
          • So the remaining two input values are 1, 2
          • In line with expectations
import { useState } from "react"; export default function App() { const list = [{ id: 0 }, { id: 1 }, { id: 2 }]; const [arr, setArr] = useState(list); const del = () => { const _arr = [...arr]; _arr.shift(); setArr(_arr); }; const renderIndex = () => arr.map((_, index) => <input key={index} />); const renderId = () => arr.map(({ id }) => <input key={id} />); <div className="App"> error: {renderIndex()} <br /> Correct: {renderId()} <br /> <button onClick={del}> delete first element </button> </div>); }Copy the code

(4) 0.1 + 0.2 precision loss

(4.1) Prior knowledge

  • Js usednumberType to represent numbers without distinctionThe integerandFloating point Numbers
  • Js through64-bit binaryCode to represent a number, followIEEE754standard
  • IEEE754
    • Four methods are specified for representing floating point numbers
    • Single precision (32 bits)
    • Double precision (64 bits)
    • Extended single precision 43 – rarely used
    • Extended double 80 – rarely used
  • The representation of a floating point number
    • Value = sign * exponent * fraction
    • The actual value of a floating point number = sign bit * exponential offset value * fraction value
    • Exponent index
    • Fraction FRACTION of a decimal number
  • Sign bit ——- 1
    • Most significant bit – is specified as a sign bit
    • 1 – bit Indicates the symbol bit
  • Index offset ——- 11
    • The second most significant e bits store the exponential part
    • Exponential offset: indicates the offset of the exponential field
    • Index offset = the actual value of the index + some fixed value
    • 11 – bit index offset
  • Decimal-fractional value ——- 52
    • The remaining F low-significant bits store the fractional portion of the significant number (significand)
    • (Default to 0 for integer parts in unspecified form and 1 for all other cases)
    • 52 – decimal place

(4.2) Numerical calculation process

  • The calculation process is mainly divided into two steps :(base conversion) and (logarithmic operation)

(4.3) Base conversion – there is precision loss

  • Converts decimal to binary according to IEEE754 standards
  • Divide a decimal number by 2, take the remainder, and take the remainder from the bottom up, the following figure

0.1 - > 0.0001100110011001... (Infinite loop) 0.2 -> 0.0011001100110011... (infinite loop) according to the limit of mantras of IEEE754, the redundant bits need to be cut off, so there is precision lossCopy the code

(4.4) Logarithmic order operation – there is precision loss

  • Because the exponential bit is not the same, the operation needs the order operation
  • There may also be loss of precision in logarithmic operations
    • If the small order codes are equated to the large order codes, in the process of shift, if data loss occurs, it is also the loss of the rightmost data bit, which will only affect the accuracy of the data, not the size of the data
    • In the computer, the method of using small order to large order to achieve
  • Refer to the article
    • Blog.csdn.net/qq_43627631…
    • Juejin. Cn/post / 684490…

(4.5)

  • Js calculation precision loss occurs in, (base conversion) and (logarithmic operation)
  • Solution: Multiply a number by 10,000, then divide by 10,000
  • Other points to note:
    • If a (decimal) number (more than 16 bits) is converted to a string, it will not be equal
      • (12345678901234567).tostring () toString "12345678901234568"

(5) The difference between XML and HTML

  • XML Extensible Markup Language
  • Effect of different
    • html
      • HTML is (display data)
    • xml
      • XML is used (to describe data) and (to store data) as a medium for persistence
      • XML will become the most common tool for data processing and data transfer
      • XML has no syntax rules, but it does have syntactic rules
  • Different grammar requirements
    • HTML is case insensitive and XML is case sensitive
    • HTML can have attribute names without values, and all attributes in XML must have corresponding values
  • The mark is different
    • HTML uses native tags, while XML has no native tags
    • HTML tags are predefined, while XML is custom and extensible

(6) THE compatibility of HTML5 tags

(6.1) New tags for HTML5header navAre not compatibleie8

  • Solution:
    • Through the document. The createElement method (‘ header ‘)
    • Set header: {display: block; }
  • The reason:
    • Internet Explorer 8 considers that the header label is a user-defined label and does not support display
    • Document.createelement (‘ header ‘) explicitly tells it that this is the tag being created
    • Then set the corresponding CSS style for the header tag to display:block
document.createElement('header');

header {
    display: block;
}
Copy the code

(7) the Object. The keys (), Object, getOwnPropertyNames (), for… The difference between the three

  • Object.keys()
    • Only its own attributes are traversed, excluding inherited attributes
    • And is an enumerable property
    • Own property + enumerable property
  • Object.getOwnPropertyNames()
    • Traverses its own properties, excluding inherited properties
    • Includes non-enumerable properties
    • Self property + enumerable property + non-enumerable property
  • for … in
    • Property of its own + enumerable property + inherited property
  • property in object
    • ‘name’ in {name: 111} // true
    • Checks whether an object contains an attribute, true and no false
    • Own property + inherited property
  • Object. The keys () and the Object. GetOwnPropertyNames ()
    • Similarities:
      • Both iterate over their own properties, neither can iterate over inherited properties
      • Both can be traversed (object and array), i.e. the argument is an array or an object
    • The difference between
      • Object.keys() = own property + enumerable property
      • Object. GetOwnPropertyNames () = + + can be enumerated attribute not enumerated attribute itself
    • so
      • Keys () is used to iterate over objects
      • Rather than using Object. GetOwnPropertyNames ()
/ / Object. The keys () / / Object getOwnPropertyNames () / / Object. The keys () / / - only through their own properties, Not including inherited / / - and can be enumerated attribute / / - ` itself + can be enumerated attribute ` / / - Object. GetOwnPropertyNames () / / - through their own properties, Not including inherited attributes // - including non-enumerable attributes // - 'own attributes + enumerable attributes + non-enumerable attributes' // - for... In / / - ` itself + can be enumerated attribute + inherited attributes ` / / - * * Object. The keys () and Object getOwnPropertyNames comparison () * * / / - similarities: // - ** can iterate over (objects and arrays)**, The parameter is an array or Object / / - differences / / - ` Object. The keys () = + can be enumerated attribute itself ` / / - ` Object. GetOwnPropertyNames () = + + can be enumerated attribute not enumerated attribute itself ` / / - So / / - generally all is the use of the Object. The keys () to traverse the Object / / - rather than using Object. GetOwnPropertyNames () const arr = [1, 2]; const obj = { name: 1, age: 2, }; Object.defineProperty(obj, "EnumerableProperty", { value: "EnumerableProperty", enumerable: true, }); Object.defineProperty(obj, "NotEnumerableProperty", { value: "NotEnumerableProperty", enumerable: false, }); const obj2 = Object.create(obj); Obj2. Extends = "extends"; // obj const keys = Object.keys(obj); const ownPropertyNames = Object.getOwnPropertyNames(obj); for (let i in obj2) { console.log("for... in", i); // extends name age EnumerableProperty } console.log(`keys`, keys); // ['name', 'age', 'EnumerableProperty'] console.log(`ownPropertyNames`, ownPropertyNames); // ['name', 'age', 'EnumerableProperty', 'NotEnumerableProperty'] // arr const keys2 = Object.keys(arr); const ownPropertyNames2 = Object.getOwnPropertyNames(arr); for (let i in arr) { console.log("for-in", i); } // 0 1 console.log(`keys2`, keys2); // ['0', '1'] console.log(`ownPropertyNames2`, ownPropertyNames2); //['0', '1', 'length']Copy the code

(8) Static methods on Object

  • Front knowledge
    • 1. What are enumerable properties and what are non-enumerable properties? How to set up
      • Enumerated properties: Refers to properties that can be traversed
      • Non-enumerable properties: Refers to properties that are not traversable
      • Object. DefineProperty (obj, Property, {value, Enumerable :true})
      • Enumerable: True means it is enumerable
(8.1) method to control the Object state Object. The preventExtensions () -- -- -- -- -- -- -- to prevent objects expand, can not add attribute Object. The seal () -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- prohibited Object configuration, can not add to delete, But you can modify object.freeze () ------------------ to freeze an Object, Cannot add or delete modify object.isextensible checking whether an Object isExtensible object.issealed () checking whether an Object is configurable object.isfrozen () checking whether an Object isFrozen(8.2) methods for the Object property model Object. GetOwnPropertyDescriptor () : get a property description of Object Object. GetOwnPropertyNames () : DefineProperty () : Define a property by describing the Object. Object.defineproperties () : Define multiple properties by describing the ObjectCopy the code

Object.preventExtensions()

  • Action: Prevents the object from expanding, that is, adding new attributes
  • Pay attention to the point
    • An error is reported if attributes are added via Object.defineProperty(obj, property, {})
    • If an attribute is added using object.a = XXX, no error is reported, but no new attribute is added
    // Object.preventExtensions() // Prevent Object extensions // that is, never add object.preventExtensions (obj); obj.e = 5; console.log(`Object.preventExtensions()1`, obj); Object.defineproperty (obj, 'f', {value: 6}) console.log(' Object.preventExtensions()2 ', obj); Uncaught TypeError: Cannot define property F, object is not extensibleCopy the code

Object. The seal () and Ojbect. Freeze ()

  • Object.seal()
    • Properties cannot be added or deleted, but can be modified
  • Object.freeze()
    • Effect: Cannot add or delete modify properties

Object.defineProperty

  • 1. The role
    • Add a property
    • Modifying a property
    • And returns this object
  • 2. Grammar
    • Object.defineProperty(obj, prop, descriptor)
      • parameter
        • Obj Specifies the object to define the property, prop specifies the name of the property to define or modify, descriptor specifies the property descriptor
      • The return value
        • The object passed to a function
      • The default
        • By default, attributes added via Object.defineProperty() are (non-modifiable)
        • Equivalent to immutable=true in property description objects
      • Attribute descriptortheTwo forms
        • Data descriptors and access descriptors,Are all objects.One descriptor: can only be one descriptor, not both
        • Data descriptor object: is a property with a value
        • Access description object: an object consisting of the get and set functions
        • (data descriptor object) and (access descriptor object) (shared) methods
          • value
            • The value corresponding to the property
          • writable
            • Value can be changed only if the value is true
            • The default is false
          • enumerable
            • Whether the property is enumerable
            • The default is false
          • configurable
            • When the value is true
              • The property’s descriptor object can be changed
              • This property can be deleted
            • The default is false
          • get set
console.log(`----------------------`); const obj3 = { a: 1 }; Object. DefineProperty (obj3, "b", {value: 2, writable: false, // Default is false. False, / / default is false, an enumeration, (can be enumerated attribute can be Object. The keys () Object. GetOwnPropertyNames () for... The property descriptor object can be modified, and the property can be deleted without any additional information, if any,}); obj3.b = 22; Console. log(' object.defineProperty () adds attributes that cannot be modified by default, immutable=true, obj3.b // 2, or 2, and is modified to 22, but if writeable=true, B the value of the attribute can be modified. Console. log(' object.keys (obj3) => own properties + enumerable properties', Object. The keys (obj3)) to the console. The log (` Object. GetOwnPropertyNames (obj3) = > + can be enumerated attribute + an enumeration `, Object.getOwnPropertyNames(obj3)) for(let item in obj3) { console.log(`for.. In => 6464x + enumerable + property ', item)} Reflect. DeleteProperty (obj3, 'b') console.log(' 6464X =true, works without any additional information. This property can be removed ', obj3)Copy the code

(9) common macro tasks and micro tasks

  • Micro tasks
    • promise
    • process.nextTick– Takes precedence at any stage of the Node lifecycle because it is a microtask
    • MutationObserver– Change the meaning of observation
  • Macro task
    • setTimeout
    • setInterval
    • setImmediate– Executed in the Check phase after the poll phase of node
    • requestAnimationFrame– Occupy the main thread
  • Extension:
    • 1. Node and browser event loops
    • 2. Why does process.nextTick take precedence over each phase of the Node event cycle?

(10) Closure

  • Conditions under which closures are generated
    • Have nested functions
    • The inner function refers to the variable of the outer function
    • Execute outer function
  • Number of closures calculated
    • The number of closures is the number of times the outer function is called.
  • The role of closures
    • 1. Make (function internal variables) in memory after (function call), (prolong the life cycle of local variables)
    • 2. Allow variables outside the function to be manipulated inside the function
    • 3. Can be used to encapsulate the module, that is, the module can manipulate internal variables, but does not pollute external variables
  • How do I clear closures
    • How to remove
      • The variable assigned by the outer function is reassigned to another value, such as a = null
    • Causes that can be cleared
      • The (function object) that contains the (closure variable) becomes (garbage object), so the closure will be cleared by the garbage collection mechanism
      • That’s because the variable also refers to the inner function

(xi) the order of the life cycle of the parent and child components in vUE

(1) the mount stage

  • Create: The parent component is created before the child component
  • Mount: Child component is mounted before parent component
Parent component -beforeCreate Parent component - Created Parent component -beforeMount child component -beforeCreate Child component - Created child component -beforeMount child component - Mounted Parent component - MountedCopy the code

(2) phase of the update

  • Parent component precedes child component beforeUpdate
  • Child component updated before parent component
Parent -beforeUpdate Child -beforeUpdate Child -updated Parent -updatedCopy the code

(3) the unMount to stage

  • Parent component precedes child component beforeUnmount
  • Child component is unmounted before parent component
Parent component -beforeUnmount Child component -beforeUnmount Child component - Unmounted Parent component -unmountedCopy the code

(4) Practice the parent-child lifecycle in VUE3 (custom instructions)

  • Vue3 optimizes the hook names in directives to be consistent with the component lifecycle, which is better than VUe2
Directive ('focus', {mounted(el) {}}) 1. Const app = vue.createApp ({}) app.directive('focus', {el) {}}) 2. Directives: {focus: {mounted(EL) {}}} 3. The hook function in the directive -created - beforeMount -mounted - mounted means called when (the parent of the tied element) is (after mounting) - Note: - Because: Mounted lifecycle hooks are executed only after mounted() of child components is executed - so: - beforeUpdate - updated - beforeUnmount - unmounted 4. -el - The element to which the hook function is bound, which can be used to directly manipulate DOM bind - an object containing the following attributes - name: the name of the directive, excluding the V-prefix -value: the binding value of the directive -oldvalue: - expression: string expression of an instruction - arg: parameters passed to an instruction, optional - MODIfiers - vnode: virtual node generated by Vue compilation - oldVnode: last virtual nodeCopy the code

(十二) plainObject

Front knowledge

  • My prototype chain article juejin.cn/post/684490…
- number string Boolean undefined symbol - object function 2 Prototype link 2.1 functions - all (functions), All uppercase (function.prototype) instances - including itself, Function.__proto__ === Function. Prototype __proto__ === function. prototype All functions are instances of the function. prototype Object - Constructor(){} Constructor.__proto__ === function. prototype All functions are instances of the function. prototype object Constructor. __proto__ === Object.prototype All function prototypes are instances of Object.prototypeCopy the code

(1) What is plainObject

  • Definition: Objects defined by Object literals {} and objects defined by object.create () are plainObjects
  • const obj = {}
  • const obj = Object.create()

(2) React-redux definition of plainObject utils

  • Analysis of the 1
    • Because:const obj = Object.create(null)
    • So:Object.getPrototypeOf(obj) === null // true
  • Analysis of 2
    • Because:const obj = {}
    • So:Object.getPrototypeOf(obj) === Object.prototype // true
PlainObject ------- /** * @param {any} obj The object to inspect. * @returns {Boolean} True if the argument appears to be a plain object. */ export default function isPlainObject(obj) { if (typeof obj ! == 'object' || obj === null) return false let proto = Object.getPrototypeOf(obj) if (proto === null) return true // PlainObject let baseProto = proto while (Object.getProtoTypeof (baseProto)! == null) {// If the prototype object of (parameter object) is not (null), i.e. satisfies the condition of while // then: assigns the prototype object layer by layer until the prototype object of the parameter object is null. Object. Prototype === null Prototype === object.getProtoTypeof (baseProto)} // 2. // Because: plainObject Object obj.__proto__ === object.protype // So: // plainObject returns true // 3 // plainObject returns true // 3 // / obj is a function // proto is function Prototype // so: When the argument is passed as a function, false is returned, Prototype // baseProto is Object. Prototype // if obj is array // proto is array. prototype // - Object.getPrototypeOf([]) === Array.prototype // - Object.getPrototypeOf(Array.prototype) === Object.prototype // // The prototype of any function is an instance of object. prototype; // The prototype of any function is an instance of object. prototype.Copy the code

(13) Background-position: 50% and 20% positioning algorithm

  • Is based on the percentage of the picture itself
  • Such as:background-position: 50%; The anchor point of the image is 50%, so it can be completely centered
  • Such as:background-position: 0; The registration point is positioned at 0% of the image, so it is the upper left corner and cannot exceed negative

(14) Processing URL

  • 2021/12/04 update
1 const url = new URL(url [, base]) - parameter - url - a DOMString representing (absolute or relative) URL - Absolute URL: Base parameter will be ignored - Relative URL: Base urL-base - The domstring-base argument to a base URL takes effect if: The first argument url is relative URL - return value - newly generated URL instance object - a 'TypeError' - !!!!!!!! is thrown if the given base URL or generated URL is not a valid URL link ----> url.searchparams () returns the same value as new URLSearchParams() - !!!!!!!! ----> new URL('https://... /? s=url').searchParams.get('s') === new URLSearchParams('? S =url').get('s') - example const url = new url ('/ API /? author=woow_wu7&age=20#head', 'http://www.baidu.com') / / equivalent to const url = new url (' http://www.baidu.com/api/?autho=woow_wu7&age=20#head ') / / href: "Http://www.baidu.com/api/?author=woow_wu7&age=20#head" / / note: 2 const URLSearchParams = new URLSearchParams(init) - parameter - init: String - Return - URLSearchParams instance - Properties on instance object - Append (key, Value) Add search key value pairs -delete (key) delete -entries () Return iterator objects - can be for... Of traversal -foreach () traversal -get (key) fetch -getall (key) -keys () -set (key, value) -sort () -tostring ()Copy the code

data

PlainObject juejin. Cn/post / 684490…