Scope and Scope Chain in js
There are two types of scopes in javascript
- Local Scope: They can only be accessed within a function
- Global scope: All scripts and functions of a Web page can access it.
javascrip has a function scope: each function can create a new scope.
Scope Chain
When looking for a variable, it looks for it from the variable object in the current context. If it is not found, it looks for it from the variable object in the parent execution context. It always finds the variable object in the global context, that is, the de-global object. This list of variable objects in multiple execution contexts is called a scope chain
About closures
The sum of the functions and the variables that are accessible within the function is a closure.
Anything that accesses a variable inside a function is called a closure. Because of the existence of the scope chain, the external variables can be accessed inside the scope and the functions are in the global scope, so the functions can access the global variables.
Closures are often used to access a variable indirectly. Closures do not cause memory leaks in general browsers (memory leaks are variables that cannot be accessed or released), but there are bug s in IE browsers because IE cannot recycle variables referenced in closures after they have been used.
Functions created through the new Function do not form closures, because functions created in this way do not contain references to the Lexical Environment in which the function was created. Closures occupy internal space, and heavy use of closures can cause stack overflow. Because closures always occupy memory until the page is destroyed, we can actively destroy them after they are used. Assigning a value of the closure function to null will destroy them.
Application scenarios for closures
- Protect the security of variables within a function
- Maintain a variable in memory
- Implement js private properties and methods by protecting variables
- Bind event parameters for nodes.
prototype
Prototype:
Function used to copy an existing instance to generate a new one. Each function in js has a prototype property that points to the prototype object of the function, and each child object derived from the prototype object has the same property. A child object is called a constructor and gets the same properties from the instance prototype. All properties and methods on the prototype are inherited by instances of the constructor, so we can define common properties and methods directly on the prototype object properties.
Prototype is the prototype of the instance object created by calling the constructor. Prototype allows all object instances to share the properties and methods it contains, so we can define object information directly in the prototype without defining it in the constructor.
Prototype chain:
The connection between the instance object and the prototype is called the prototype chain. Each object has its own prototype object, and one layer at a time forms a chain of prototypes. The top end of the prototype chain is OBje.prototype, he has no prototype object (null)
js has a proto built-in property when creating an object, which points to the prototype object of the function object that created it.
Throttle and anti-shake
Throttle:
High frequency event trigger, trigger a large number of events in a short time.
Solution: Design a valve-like function that will fail after one execution and reactivate after that time period. With setTimeout implementation, add a variable valid representing the state.
function throttle(fn,delay){ let valid = true return function() { if(!valid){ //Receive no guests at rest return false } // Working hours, executing functions and invalidating status bits during intervals valid = false setTimeout(() => { fn() valid = true; }, delay) } } /* Note that the throttling function is more than just this implementation. For example, instead of setTimeout at all, state bits can be replaced by time stamps, which can then be used to determine if the time stamp difference is greater than the specified interval. You can also directly use the returned tag from setTimeout as a criterion - to determine if the current timer exists, and if it exists to indicate that it is still cooling down and to eliminate the timer from indicating activation after fn execution, the principle is the same */ // As before function showTop () { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log('Scrollbar position:' + scrollTop); } window.onscroll = throttle(showTop,1000)
Anti-shake:
Only executes once in N seconds after triggering a high frequency event, and recalculates the event if triggered again in n seconds.
Solution: With the setTimeout function and a variable to save the timing, consider maintaining global purity, and implement with closures
function debounce(fn,delay){ let timer = null //With Closure return function() { if(timer){ clearTimeout(timer) } timer = setTimeout(fn,delay) // Simplified Writing } } // Then the old code function showTop () { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log('Scrollbar position:' + scrollTop); } window.onscroll = debounce(showTop,1000) // For the sake of observing the effect, we take the break value of a big point and configure it as needed.
Curitization and Anti-Curitization
Curitization:
Receive some parameters in advance, delay execution, do not output results immediately, return a function to receive the remaining parameters, also become a partial calculation function, this is a step-by-step process to receive parameters
function currying(fn,...rest1){ return function(...rest2){ //apply is used here to pass parameters in the form of arrays directly into the original function null because there is no need to change this return fn.apply(null,rest1.concat(rest2)); } }
function sayHello(name,age,fruit){ console.log(`My name is ${name},I ${age}Years old, I like to eat ${fruit}`); } //Pass in the first parameter let curryingShowMsg = currying(sayHello,'Xiao Ming'); //Execute incoming remaining parameters curryingShowMsg(22,'Mango');
Anti-Curitization:
In order to make the method usable in a wider context and to use anti-currying, you can deconstruct the native method so that any object has a method of the native object. When we invoke a method of an object, we don't have to worry about whether the object has the method. This is a feature of dynamic type language, which allows an object to borrow a method that doesn't belong to it by anti-currying.
function curryingHelper(fn,len){ //Let's start with a basic knowledge point, fn.length returns the number of parameters this method needs to pass in //The first run here passes fn. Recursion after length uses incoming len as the number of remaining parameters const length = len || fn.length; return function(...rest){ //Determines if the parameter passed in this time is greater than or equal to the remaining parameter If it is not recursive return to the next method to continue the pass return rest.length >= length ? fn.apply(this,rest) : curryingHelper(currying.apply(this,[fn].concat(rest)),length-rest.length) } } //Or just the sayHello function let betterShowMsg = curryingHelper(sayHello); //Automatic control of number of parametric layers betterShowMsg('zyx')(22)('Grape'); betterShowMsg('zyx',22)('Grape');
Differences between async/await and promise
Promise
promise is an asynchronous programming solution that is more powerful than callback functions, and promises are like containers containing the results of events that will not be executed until the future. Once generated, these results cannot be changed. promise solves the problem of callback hell, but the vertical development forms a callback chain, which is also ugly when encountering complex scenes
Source code:
There are two arrays that hold methods for successful callbacks and methods for failed callbacks. The methods of resolve and reject are called based on the status returned by promise, and the methods in each array are traversed and executed.
const PENDING = 'pending'; //Initial state const FULFILLED = 'fulfilled'; // Success Status const REJECTED = 'rejected'; // Success function Promise(extutor){ let self = this; self.status = PENDING; // Set state // Array holding successful callbacks self.onResolveCallbacks = []; // Array to hold failed callbacks self.onRejectedCallbacks = []; function resolve(value){ if(self.status === PENDING){ self.status = FULFILLED; self.value = value; self.onResolveCallbacks.forEach(cb => cd(self.value)) } } function reject(reason){ if(self.status === PENDING){ self.status = REJECTED; self.value = reason; self.onRejectCallbacks.forEach(cb => cd(self.value)) } } try{ excutor(resolve, reject) } catch(e) { reject(e) } }
Simple implementation
//Realization of minimalism class Promise { callbacks = []; constructor(fn) { fn(this._resolve.bind(this)); } then(onFulfilled) { this.callbacks.push(onFulfilled); } _resolve(value) { this.callbacks.forEach(fn => fn(value)); } } //Promise Application let p = new Promise(resolve => { setTimeout(() => { console.log('done'); resolve('5 second'); }, 5000); }).then((tip) => { console.log(tip); })
Promise's constructor receives a callback, which is the executor. resolve and reject are also two functions responsible for changing the state and value of the promise instance. The callback in the then function is executed after the state changes. The then method places the callback in the execution queue and executes the functions in the queue after the promise's state changes.
all method
Promise.all() receives an array of parameters and returns a new promise instance. The promise returned by the heart will not resolve until all the promises in the array are resolved or all are executed. Any one of the promises in the array fails (reject), and the newly returned promises fail, returning the value of the first rejected failure state.
Promise. The data order and romise in the array of all successful results. All receives the array in the same order, that is, the result of p1 comes first, even if the result of p1 is later than that of p2. This brings a huge benefit: In the process of front-end development requesting data, occasionally you encounter scenarios where multiple requests are sent and data is acquired and used in the order of requests, using Promise.all can undoubtedly solve this problem.
race method
Similar to the all method, it also receives an array of parameters, returns a new promise, and which promise in the array returns which result quickly, regardless of success or failure.
async/await
async/await is also an asynchronous programming solution that follows the syntax sugar of the generator function, has a built-in executor, and automatically executes without additional calls and outputs the results, returning a promise object.
The async/await code looks more concise, making the asynchronous code more like the synchronous code. The essence of await is to provide syntax sugar equal to the synchronous effect of waiting for asynchronous return, and the next sentence will not be executed until this one is executed.
async/await is a promise-based implementation, which is a modified promise and cannot be used in ordinary callback functions.
finally method
Returns a promise, which executes a callback function at the end of the promise, regardless of whether the result is a failure or a success. The status and value of returning a new promise depends on the original promise
allSettled method
Returns a promise, requiring code to execute after multiple promises have succeeded. Once all promises have been completed, this point in time can be obtained. The returned cardiac promise is always resolve d, and the value is a description of the results of all promises.
const promise1 = Promise.resolve(3); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo')); const promises = [promise1, promise2]; Promise.allSettled(promises). then((results) => results.forEach((result) => console.log(result.status))); // expected output: // "fulfilled" // "rejected"
graphql facebook development
axios concurrency
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-yGGItZDp-16281739105) (C:UsersytAppDataRoamingTyporatypora-user-imagesimage-2027.png)]
koa
No middleware, all third-party Middleware
Ctx. Body ctx. Both res.end can return information
app.use(async(context,next)=>{
})
h((result) => console.log(result.status)));
// expected output:
// "fulfilled"
// "rejected"
# Graphql Facebook development axios Concurrent [Outer Chain Picture Transfer in Progress...(img-yGGItZDp-1628175239105)] ## koa No middleware, all third-party Middleware ctx.body ctx.res.end Can return information app.use(async(context,next)=>{ }) [Outer Chain Picture Transfer Failed,Source station may have anti-theft chain mechanism,It is recommended to save the picture and upload it directly(img-zhVYqbyK-1628175239108)(C:\Users\yt\AppData\Roaming\Typora\typora-user-images\image-20210804215048169.png)]