In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "some front-end basic knowledge collation". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought and go deep into it slowly. Let's study and learn "some front-end basic knowledge collation"!
Call, bind, apply implementation
/ / call Function.prototype.myCall = function (context) {context = context? Object (context): window context.fn = this; let args = [... arguments] .slice (1); const result = context.fn (.. ARGs); delete context.fn; return result;} / / apply Function.prototype.myApply = function (context) {context = context? Object (context): window; context.fn = this; let args = [... arguments] [1]; let result; if (args.length = 0) {result = context.fn ();} else {result = context.fn (args);} delete context.fn; return result;} / / bind Function.prototype.myBind = function (context) {let self = this; let args = [. Arguments] .slice (1) Return function () {let newArgs = [... arguments]; return self.apply (context, args.concat (newArgs));}}
Prototype and prototype chain
Each JavaScript object (except null) is associated with another object when it is created, and the associated object is the prototype. The _ _ proto__ property that every JavaScript object (except null) has points to the object's prototype. All the objects in JavaScript are inherited from its prototype object, and the prototype is also an object, and it also has its own prototype object, so it goes up layer by layer, forming a structure similar to a linked list, which is the prototype chain. Each object "inherits" properties from the prototype.
Both the instance object and the constructor can point to the prototype, which can point to the constructor, not to the instance (because there can be multiple instances).
The prototype object has two properties, constructor and _ _ proto__.
Function Person () {} var person = new Person (); / / instance prototype = constructor prototype person.__proto__ = Person.prototype / / true / / prototype constructor = = constructor Person.prototype.constructor = Person / / true
React diff
React transforms the problem of O (n3) complexity into the problem of O (n) complexity by formulating a bold diff strategy.
React optimizes the algorithm of tree diff through the strategy of hierarchical difference.
Hierarchical comparison of the tree, the two trees will only compare the nodes at the same level.
React optimizes the algorithm of component diff through the strategy of generating similar tree structure of the same kind and different tree structure of different kind.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
If it is the same type of component, continue to compare virtual DOM tree according to the original policy.
If not, the component is judged to be dirty component, replacing all child nodes under the entire component.
For the same type of component, it is possible that its Virtual DOM has not changed, if you can know this exactly, it can save a lot of diff computing time, so React allows users to use shouldComponentUpdate () to determine whether the component needs to be diff.
React optimizes the algorithm of element diff by setting the policy of unique key.
It is recommended that maintaining a stable DOM structure will help improve performance when developing components
Traversing object
Summary of object traversal methods:
For...in: traverses the object itself, including inherited, enumerable, and Symbol-free properties.
Object.keys (obj): traverses the object itself, without inheritance, enumerable, and without attributes of Symbol. [values, entries]
Object.getOwnPropertyNames (obj): traverses the object itself, without inheritance and Symbol attributes, regardless of whether it is enumerable or not
Object.getOwnPropertySymbols (obj): traverses the object itself, excluding inheritance, all Symbol properties, whether enumerable or not
Reflect.ownKeys (obj): traverses the object itself, excluding inheritance, all key names, whether Symbol or not, and enumerable.
Object other methods:
JSON.stringify (): only serializes the object itself, without inheritance, enumerable, and without the Symbol attribute. [function,undefined, Symbol will be lost, set and map will be processed into empty objects]
Object.assign (): copies only the object itself, without inheritance, and enumerates properties, regardless of whether it is Symbol or not. [all data type attribute values]
Load script asynchronously
By default, browsers load JavaScript scripts synchronously, meaning that the rendering engine stops when it encounters a tag, waits until the script is executed, and then continues to render down. If it is an external script, you must also include the time when the script is downloaded.
Load script asynchronously: defer and async.
The difference between defer and async is that defer will not be executed until the whole page is rendered normally in memory (the DOM structure is fully generated, and other scripts are completed). Once the async is downloaded, the rendering engine will interrupt the rendering, and then continue rendering after executing this script. In a word, defer is "render and then execute", and async is "download and execute". In addition, if there are multiple defer scripts, they will be loaded in the order in which they appear on the page, and multiple async scripts cannot guarantee the loading order.
Browsers with type= "module" load asynchronously without blocking the browser, that is, wait until the entire page is rendered, and then execute the module script, which is equivalent to opening the defer attribute of the tag.
The difference between ES6 Module and CommonJS Module
The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value.
The CommonJS module is loaded at run time, and the ES6 module is the compile-time output interface.
Because CommonJS loads an object (that is, the module.exports property), the object is generated only after the script has been run. While the ES6 module is not an object, its external interface is only a static definition, which will be generated in the code static parsing phase.
The require () of the CommonJS module is the synchronous loading module, and the import command of the ES6 module is loaded asynchronously, with an independent module dependent parsing phase.
Reflow Reflow and redraw Repaint
Reflow: the size or position of the element changes, triggering a relayout, causing the render tree to recalculate the layout and render. Backflow occurs at least once the first time the page is loaded.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Add or remove visible DOM elements
The position of the element has changed
The size of the element has changed
The content changes (such as a text change or a picture replaced by a picture of a different size)
When the page begins to render (this is inevitable)
The window size of the browser changes because the reflux calculates the position and size of the element based on the size of the viewport.
Redraw: the appearance and style of the element changes without affecting the layout (excluding width, height, size, position, etc.).
Such as: outline, visibility, color, background-color. Etc.
The cost of Reflow is much higher than that of Repaint. Every node in DOM Tree has a reflow method, and the reflow of a node is likely to lead to the reflow of the child node, or even the parent node and the peer node. Redrawing is bound to trigger redrawing, and redrawing is not necessarily redrawn.
Reduce redrawing and reflow
1.CSS method
Replace display: none with visibility, because the former will only cause redrawing and the latter will cause reflow
Avoid using table layouts, as a small change may result in a relayout of the entire table.
Avoid setting multi-layer inline styles, and CSS selectors match search from right to left to avoid too many node levels.
Apply animation to elements whose position attribute is absolute or fixed to avoid affecting the layout of other elements, which is just a redraw rather than reflux. At the same time, you can choose requestAnimationFrame to control the animation speed.
Avoid using CSS expressions, which may cause a backflow.
Set a node that is frequently redrawn or reflowed as a layer, and the layer can prevent the rendering behavior of that node from affecting other nodes, such as will-change, video, iframe, and so on. The browser will automatically change the node into a layer.
CSS3 hardware acceleration (GPU acceleration), using css3 hardware acceleration, allows animations such as transform, opacity and filters to avoid redrawing. However, other properties of animations, such as background-color, can still cause redrawing, but it can still improve the performance of these animations.
2.JavaScript method
To avoid frequent style manipulation, it is best to override the style property at once, or define the style list as class and change the class property at once.
Instead of manipulating DOM frequently, create a documentFragment, apply all DOM actions to it, and finally add it to the document.
Avoid frequently reading properties that cause reflow / redrawing, and if you do need to use them multiple times, cache them with a variable.
CSS3 hardware acceleration (GPU acceleration)
CSS3 hardware acceleration, also known as GPU acceleration, is an optimization scheme that uses GPU to render and reduce CPU operations.
Render tree-> render elements-> layers-> GPU rendering-> browser compound layer-> generate the final screen image.
After the browser obtains the render tree, the rendering tree contains a large number of rendering elements, each rendering element will be divided into a layer, and each layer will be loaded into the GPU to form a rendering texture. Transform in GPU will not trigger repaint, and eventually these layers that use transform will be processed by a separate compositor process.
CSS3 triggers hardware acceleration properties:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Transform
Opacity
Filter
Will-change
Http request method
HTTP1.0 defines three request methods: GET, POST, and HEAD methods.
HTTP1.1 has added five request methods: OPTIONS, PUT, DELETE, TRACE and CONNECT methods.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
OPTIONS: a pre-check request that can be used to detect the http methods allowed by the server. When initiating a cross-domain request, due to security reasons, when a certain condition is triggered, the browser will automatically initiate an OPTIONS request, that is, a CORS pre-check request before the formal request. If the server accepts the cross-domain request, the browser will continue to initiate the formal request.
HEAD: request a response from the server that is consistent with the GET request, except that the response body will not be returned to get the header.
GET: make a request to a specific resource. Note: the GET method should not be used in operations that produce "side effects"
POST: submit data to a specified resource for processing requests (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and / or modification of existing resources.
PUT: uploads the latest content to the specified resource location
DELETE: request the server to delete the resource identified by Request-URL
TRACE: echo requests received by the server, mainly for testing or diagnostics
The CONNECT:HTTP/1.1 protocol is reserved for proxy servers that can change the connection to a pipeline.
Js determines the data type
1. Typeof operator
For basic types, with the exception of null, correct results can be returned.
For reference types, the object type is returned except for function.
For null, returns the object type.
Returns the function type for function.
2. Instanceof
Used to determine whether An is an instance of B, the prototype is detected. Instanceof can only be used to determine whether two objects belong to an instance relationship, not to determine which type an object instance belongs to.
The main implementation principle of instanceof is as long as the prototype of the variable on the right is on the prototype chain of the variable on the left.
3. Constructor
Null and undefined are invalid objects. There will be no constructor.
The constructor of the function is unstable, which is mainly reflected in the custom object. When the developer rewrites the prototype, the original constructor reference will be lost and the constructor will default to Object. In order to standardize development, it is generally necessary to re-assign values to constructor when rewriting object prototypes.
4. ToString
ToString () is the prototype method of Object, which is called and returns the [[Class] of the current object by default. This is an internal property in the format [object Xxx], where Xxx is the type of object.
Browser event model
There are three stages in DOM event flow (event flow): the event capture phase, the target stage and the event bubbling phase.
/ / useCapture:true, that is, using event capture method window.addEventListener ("click", function (e) {console.log ("window capture");}, true); / / useCapture:false [default is false], that is, event bubbling method window.addEventListener ("click", function (e) {console.log ("window bubble");}, false)
The binding events of the target element (clicked element) occur in the target phase, and the binding bubble phase code is written before the binding capture code, so the rule of first capture and then bubbling will not be followed on the target element. instead, the event that binds first occurs first.
It is not a target element, and the events bound to it follow the rule that capture occurs first and bubbles later.
E.stopPropagation (): prevents the event from propagating. It can not only prevent the spread of the event in the bubbling stage, but also prevent the spread of the event in the capture stage.
E.preventDefault (): the default behavior of blocking events. The default behavior is: click the a tag to jump to another page, drag a picture to the browser and automatically open it, click the submit button of the form to submit the form, etc.
Http caching: force caching and negotiation caching
A good caching strategy can reduce the repeated loading of resources and improve the overall loading speed of web pages.
Caching principle
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
When the browser loads the resource, it determines whether the strong cache is hit according to the expires and cache-control of the request header. If so, the browser will read the resource directly from the cache and will not send the request to the server.
If the strong cache is not hit, the browser sends a request to the server and verifies that the negotiation cache is hit by last-modified and etag. When a request for cache verification is made to the server, the server will return 200 ok to return normal results or 304 Not Modified (no body) to indicate that the browser can use the local cache file. The response header of 304 can also update the expiration time of cached documents at the same time
If neither of the first two hits, load the resource directly from the server.
Mode of realization
Strong caching is implemented through Expires and Cache-Control.
The negotiation cache is managed using two pairs of Header, [Last-Modified,If-Modified-Since] and [ETag, If-None-Match].
Expires
Expires is a header proposed by http1.0 that represents the expiration time of resources. It is an absolute time and is returned by the server. Expires is limited to the local time, which may cause cache invalidation if the local time is modified.
Expires: Wed, 11 May 2018 07:20:00 GMT
Cache-Control
Cache-Control appears in HTTP / 1.1and takes precedence over Expires, indicating relative time.
No-store: no cache. Nothing about client requests and server responses must be stored in the cache. Each request initiated by the client downloads the complete response content. No-cache: caching can be revalidated. Each time a request is made, the cache sends the request to the server, and the server verifies that the cache described in the request has expired. If it does not expire (return 304), the cache uses the local cache copy. Private: only client browser caching is allowed. Public: allows all users to cache. Max-age=:, such as intermediate proxy, CDN, and so on, represents the maximum time that a resource can be cached. Relative to Expires, max-age is the number of seconds from the time the request was initiated. For those files that will not change in the application, you can usually manually set a certain length of time to ensure that the cache is valid, such as images, css, js and other static resources. Must-revalidate: triggers cache verification. Verify its status and expired caches will not be used
Last-Modified,If-Modified-Since
Last-Modifie indicates the last modification date of the local file, and the browser will add If-Modified-Since to request header (the value of the last returned Last-Modified) to ask the server whether the resource has been updated after that date, and if so, the new resource will be sent back.
However, if you open the cache file locally, it will cause the Last-Modified to be modified, so ETag appears in HTTP / 1.1.
ETag 、 If-None-Match
Etag is like a fingerprint. Changes in resources will lead to changes in ETag, which has nothing to do with the last modification time. ETag can guarantee that each resource is unique.
The header of If-None-Match will send the last returned Etag to the server, asking if the Etag of the resource has been updated, and if there is any change, the new resource will be sent back.
ETag has a higher priority than Last-Modified.
The specific reasons for using ETag are mainly based on the following situations:
Some files may be changed periodically, but their contents do not change (only the modification time is changed). At this time, we do not want the client to think that the file has been modified and re-GET it.
Some files are modified very frequently, such as making changes in less than a second (for example, N times in 1 second). The granularity that If-Modified-Since can detect is s-level, and this modification cannot be judged (or UNIX records MTIME can only be accurate to seconds).
Some servers cannot accurately get the last modification time of the file.
Anti-shaking and throttling
Anti-shake: when you call a method frequently, it does not execute, but only if you do not call it again within a specified interval.
Throttling: a function can only be triggered once in a unit of time. If the function is triggered multiple times per unit of time, it will only take effect once.
Anti-shaking
Function debounce (fn, wait) {let time = null; return (function () {const context = this; const args = arguments; if (time) {clearTimeout (time); time = null;} time = setTimeout (() = > {fn.call (context, args);}, wait);});}
Throttling
Function throttle (fn, wait) {let lastTime; return (function () {const context = this; const args = arguments; let nowTime = + new Date (); if (nowTime > lastTime + wait | |! lastTime) {fn.call (context, args); lastTime = nowTime;}})
Difference between size and unit
Px: pixels.
Em: the reference object is the font-size of the parent element and has the characteristic of inheritance. If the font-size is defined by itself, the 1em is not a fixed value throughout the page.
Rem: font-size calculations relative to the root element html, unlike em, do not depend on the font size of the parent element, causing confusion.
Vw: window width, 1vw equals 1% of window width.
Vh: window height, 1vh equals 1% of window height.
Vm:min (vw, vh).
%: is the ratio set relative to the size of the parent element, the element of position:absolute; is relative to the parent element that has been positioned, and the element of position:fixed; is the relative visual window.
The default font of the browser is 16px, and body sets font-size:62.5%, so 1rem = 62.5% * 16=10px.
Google browser forces the minimum font to be 12. Even if it is set to 10px, it will eventually be displayed as 12px. When the font-size of html is set to 10px, the calculation of the child node rem is still based on 12px.
Box-sizing
Content-box: this is the default. The height and width of the entire element is the element content.
Border-box: in this case, the width and height attribute values you set are for the entire element, including border,padding, and element content.
Function declarations and function expressions
/ / function declaration function wscat (type) {return 'wscat';} / / function expression var oaoafly = function (type) {return "oaoafly";}
There is a mechanism for promoting variable declarations in the JavaScript interpreter, that is, function declarations are promoted to the front of the scope, even if the code is written at the bottom.
Functions created with function expressions are assigned at run time and cannot be called until the expression assignment is complete
Function declarations are promoted during JS parsing, so the function can be called in the same scope, no matter where the function declaration is defined. The value of the function expression is determined at JS runtime, and the function cannot be called until the expression assignment is complete. This slight difference may lead to unexpected bug in JS code, leaving you in an inexplicable trap.
Event Loop EventLoop
JavaScript is a single threaded scripting language.
All synchronous tasks are executed on the main thread, forming an execution stack (Execution Context Stack); while asynchronous tasks are placed in the Task Table (asynchronous processing module), when the asynchronous task has a run result, the registered callback function is moved to the task queue (two queues).
Once all the synchronous tasks in the execution stack are executed, the engine reads the task queue and then takes out the first task in the task queue and runs it on the execution stack. (all asynchronies that will be entered refer to the part of the code in the event callback)
As long as the main thread is empty, the task queue is read, and the process is repeated over and over again, which is called an event loop.
Macro task and micro task
Macro tasks enter one queue, micro tasks enter another queue, and micro tasks are better than macro tasks.
Macro tasks: script (overall code), setTimeout, setInterval, Imax O, event, postMessage, MessageChannel, setImmediate (Node.js)
Micro tasks: Promise.then, MutaionObserver, process.nextTick (Node.js)
The macro task enters a queue, while the micro task enters a different queue, and the micro task is better than the macro task.
Promise
1. Promise.all: all fulfilled before entering then, otherwise catch 2. Promise.race: any return, whether fulfilled or rejected, enter the corresponding then/catch 3. Promise.allSettled: all return, whether fulfilled or rejected, enter then 4. Promise.any: any one returns fulfilled, enter then, otherwise catch
Virtual dom principle
Virtual DOM is an abstraction of DOM, which is essentially a JavaScript object, which is a more lightweight description of DOM.
The difference between arrowhead function and ordinary function
The grammar is more concise and clear
If you do not bind this, you will capture the this value of the context in which it is located as your own
The this point inherited from the arrow function will never change.
.call () / .apply () / .bind () cannot change the direction of this in the arrow function
Cannot be used as a constructor because you cannot call call,apply; without a prototype attribute without your own this, and the new command needs to assign the prototype of the constructor to the _ _ prpto__ of the new object when executed.
Without your own arguments, accessing arguments in the arrow function actually gets the value in the outer local (function) execution environment. If you want to, you can use the rest parameter instead.
No prototype prototype, point to undefined
Cannot use the yeild keyword
New
The new keyword does the following:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Create an empty simple JavaScript object (that is, {})
Link the object (set its _ _ proto__) to the prototype of the constructor function
Use the newly created object as the context of the this
Return. If the function does not return an object, it returns this.
Function newFunc (father,... rest) {/ / first create an empty object var result = {}; / / assign the prototype of the empty object to the prototype of the constructor function result.__proto__ = father.prototype; / / change the inner this of the constructor function and point it to the newly created empty object var result2 = father.apply (result, rest) If ((typeof result2 = 'object' | | typeof result2 = =' function') & & result2! = = null) {return result2;} return result;}
Horizontal and vertical centralization
Horizontal center
Text-align: center; inline elements apply
Margin: 0 auto; for block-level elements
Width: fit-content; if the child element contains the float:left attribute, in order to center the child element horizontally, set the width of the parent element to fit-content and cooperate with margin.
.parent {width:fit-content; margin:0 auto;}
Flex
.parent {display: flex; justify-content: center;}
Box model, using flex 2009 version
.parent {display: box; box-orient: horizontal; box-pack: center;}
Transform
Son {position: absolute; left: 50%; transform: translate (- 50%, 0);}
Two different absolute positioning methods
.son {position: absolute; width: fixed; left: 50%; margin-left:-0.5 * width;} .son {position: absolute; width: fixed; left: 0; right: 0; margin: 0 auto;}
Vertical center
Single-line text, line-height
Inline block-level elements, aided by display: inline-block, vertical-align: middle; and pseudo elements
.parent:: after, .son {display:inline-block; vertical-align:middle;} .parent:: after {content:''; height:100%;}
Vertical-align . Vertical-align takes effect only when the parent layer is td or th. It is not supported by default for other block-level elements, such as div, p, etc. In order to use vertical-align, we need to set the parent element display:table and the child element display:table-cell;vertical-align:middle
Flex
.parent {display: flex; align-items: center;}
Box model
.parent {display: box; box-orient: vertical; box-pack: center;}
Transform
.son {position: absolute; top: 50%; transform: translate (0,-50%);}
Two different absolute positioning methods
.son {position: absolute; height: fixed; top: 50%; margin-top:-0.5 * height;} .son {position: absolute; height: fixed; top: 0; bottom: 0; margin: auto 0;}
Flex, box model, transform, absolute positioning, these methods are suitable for both horizontal and vertical centering.
Sort
Bubbling sort
Function bubbleSort (arr) {const len = arr.length; for (let I = 0; I
< len - 1; i++) { for (let j = i + 1; j < len; j++) { if (arr[j] < arr[i]) { [arr[j], arr[i]] = [arr[i], arr[j]]; } } } return arr; } 选择排序 选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。 function selectionSort(arr) { const len = arr.length; for (let i = 0; i < len - 1; i++) { let index = i; for (let j = i + 1; j < len; j++) { if (arr[j] < arr[index]) { index = j; } } if (index !== i) { [arr[i], arr[index]] = [arr[index], arr[i]]; } } return arr; } 插入排序 插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。 function insertionSort(arr) { const len = arr.length; for (let i = 1; i < len; i++) { let j = i - 1; const value = arr[i]; while (arr[j] >Value & & j > = 0) {arr [j + 1] = arr [j]; arr [j + 1] = value;} return arr;}
Merge and sort
Merge sorting is an effective sorting algorithm based on merge operation. This algorithm is a very typical application of divide-and-conquer (Divide and Conquer). Merge sorting is a stable sorting method. Order each subsequence first, and then order the segments of the subsequence. If two ordered tables are merged into one ordered table, it is called 2-path merging.
Function mergeSort (arr) {/ / uses a top-down recursive method var len = arr.length; if (len < 2) return arr; const middle = Math.floor (len / 2); let left = arr.slice (0, middle); let right = arr.slice (middle); return merge (mergeSort (left), mergeSort (right);} function merge (left, right) {let result = [] While (left.length & & right.length) {if (left [0])
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.