“This is the third day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

Handwritten code examples

implementationObject.create

Object.create: Creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.

const mycreate = function(obj){
    function F(){}
    F.prototype=obj
    return new F()
}
Copy the code

Native implementation jSONP

The

Var script = document.createElement('script'); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://localhost:8080/users? username=xbc&callback='+callbackName; document.body.appendChild(script); Function callbackName(res) {data = json.stringify (res) console.log(data); } ps: specify the function name callbackNameCopy the code

Natively implements HTTP requests

Catch onReadyStatechange with new XMLHttpRequest().

Important: XMLHttpRequest const getJSON = function (url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); // xhr.setRequestHeader("Content-Type", "application/json"); xhr.open("GET", url); xhr.onreadystatechange = function () { if (xhr.readyState ! == 4) return; / / a status code of 200 to 300 or 304 between said this request has been successfully the if ((XHR) status > = 200 && XHR. Status < 300) | | XHR. Status = = = 304) { resolve(xhr.responseText); } else { reject(new Error(xhr.responseText)); }}; xhr.send(); //xhr.send(data) POST }); }; // function createXHR() {// if (window.xmlhttprequest) {// return new XMLHttpRequest(); // } else { // return new ActiveXObject('Microsoft.XMLHttp'); //} // ps: main attribute on ready state changeCopy the code

Sort an array

1. – the sort function

Const arr=[1,30,4,21,99] arr.sort((a,b)=>{return a-b; }) //[1, 4, 21, 30, 99] //ps: b-a; Example: arr.sort((a,b)=>{return a.key-b.keey})Copy the code

2. Bubble

Contrast in pairs, reverse order, then swap

Const arr=[1,20,4,21,99,88] for(let I =0; i<arr.length-1; i++){ for(let n=0; n<arr.length-i-1; N++) {if (arr [n] > arr) [n + 1] {let x = arr [n] arr [n] = arr (n + 1) arr (n + 1) = x}}} / /,4,21,30,88,99 [1] / / ps: arr [n] < arr (n + 1); Big to smallCopy the code

3. The fast row

First find a base number from the array, split the array into two parts: greater than the base number and less than the base number. Then repeat the second step for the left and right ranges until each range has only one number

/ / ideas: First find a base number from the array, split the array into two parts: greater than the base number and less than the base number. Then repeat the second step for the left and right ranges. Const arr=[1,20,3,21,99,88] function quick(arr){if(arr. Length <=1) return arr; Let the left = [], right = [], mid = arr. Splice (0, 1) [0] for (let I = 0; i<arr.length; i++){ if(arr[i]<mid){ left.push(arr[i]) }else{ right.push(arr[i]) } } return quick(left).concat(mid,quick(right)) } // [1, 3, 20, 21, 88, 99] // arr[I]>mid; Big to smallCopy the code

Array merge & deduplicate

// In 2021, extend the operator. (of course a lot of the map, the key value to heavy, filters, etc.) const = a = [1, 2, 3] const b (4 and 6) const c = [... new Set ([... a, b])]; //[a,b,c,d,e,f]Copy the code

A nonnull statement does not contain 0

let value=0 if((value?? "')! == "){console.log(' not null ')} == ") returns true. When value is ", the result is ("! == ") returns false.Copy the code

Key: null value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand. What’s more? The order of operations between operators and other logical operators is not explicitly stated, so () is used.

copy

Let obj = {name: 'zhang' age: '18' grades:,99,58,68 [88]} / / shallow copy let obj2 = {... Parse (json.stringify (obj)); //ps: Use it according to the actual scenario. For complex scenarios, you can use the tool library, such as LodashCopy the code

Prototype chain inheritance

Constructor (const constructor); constructor (const constructor); constructor (const constructor);

/ / the Superclass method (Superclass) function Superclass () {enclosing supName = "I am the parent class"} / / Superclass. The parent class to add prototype method. The prototype showSupName = Function () {console.log(this.supname)} // Subclass(Subclass) function Subclass() {this.subname = "I am a Subclass"} /** * 1 Subclass.prototype = new Superclass(); subclass.prototype = new Superclass(); Ttf_subclass. Prototype. Constructor = ttf_subclass ttf_subclass / / add the prototype method. The prototype. ShowSubName = function () { Console. log(this.subname)} var sub = new Subclass(); sub.showSupName(); Call (thisArg, arg1, arg2...); ; Method provides the subclass's this value to the parent class to implement */Copy the code

Proxy is used to monitor data changes and update the DOM

Create a proxy object, set the property value hostage to handler.set(), and update the innerHTML

< div id = "name" > < / div > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- gorgeous line -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- let data = {name: } const handler = {set: Function (obj, prop, val) {console.log(obj[prop], 'monitor set changes ', obj, prop, val) obj[prop] = val; observer(); }}; const p = new Proxy(data, handler); Document.getelementbyid ('name').innerhtml = p.name // setTimeout(() => {p.name = 'Posei'}, 2000); Function Observer () {document.getelementById ('name').innerhtml = p.name} ps:**Proxy** Interception and customization of basic operations (such as property lookup, assignment, enumeration, function calls, etc.)Copy the code

Note: Handler objects that do not define a catcher retain the default behavior of the source object and vice versa. Object.defineproperty can also be implemented, but there are a lot of disadvantages, I try to use the good ones, at least I do.

At the end

It is a review of the basic notes, no in-depth, no need to bar! Mainly record the implementation principle, continuous update.