Juejin. Cn/post / 684490…

Lazy loading & preloading

Lilywei739. Making. IO / 2017/02/06 /… www.geekjc.com/post/58d94d…

Anti-shake and throttling

Juejin. Cn/post / 684490… Juejin. Cn/post / 684490…

Deep copy

Array deduplication, array out of order

Inheritance (ES5/ES6)

Realize the promise

Realize the promise. All

Realize the promise. Retry

Wrap a synchronous callback as a Promise

Write a function that controls the maximum number of concurrent requests

The realization of the json

eventEmitter(emit,on,off,once)

Implement instanceof

Implement new

Implement array flat, filter and other methods

lazyMan

Function currying

How to implement const in ES5 environment

instanceof

EncodeURIComponent & decodeURIComponent usage

xhr & ajax

JUEJIN. CN/POST / 684490…

How to write a GET request in native JS? The following code takes only 3 lines:

let xhr = new XMLHttpRequest();
xhr.open("GET", "/list");
xhr.send();
Copy the code

How do I write a POST request with native JS? As shown below:

Sorting algorithm

instanceof

Instanceof can correctly determine the type of an object because the internal mechanism is to determine if the prototype of the object can be found in the prototype chain.

function instanceof(left, right) {
    // Get the prototype of the type
    let prototype = right.prototype
    // Get the prototype of the object
    left = left.__proto__
    // Determine whether the type of the object is equal to the prototype of the type
    while (true) {
    	if (left === null)
    		return false
    	if (prototype === left)
    		return true
    	left = left.__proto__
    }
}
Copy the code

Hand write call, apply, bind

call

Function.prototype.myCall = function(context, ... args) { context = context || window let fn = Symbol() context[fn] = this let result = context[fn](... args) delete context[fn] return result }Copy the code

apply

Function.prototype.myApply = function(context) { context = context || window let fn = Symbol() context[fn] = this let result if (arguments[1]) { result = context[fn](... arguments[1]) } else { result = context[fn]() } delete context[fn] return result }Copy the code

bind

Function. The prototype. MyBind = Function (context) {var _this = this var args = [r].... the arguments slice (1) / / return a Function to return Function F() {if (this instanceof F) {return new _this(... args, ... arguments) } return _this.apply(context, args.concat(... arguments)) } }Copy the code

Storage class implementation, so that the object as a singleton, based on localStorage encapsulation. SetItem (key,value) and getItem(key)?

Class Storage {static create() {if (! Storage.instance) { Storage.instance = new Storage(); } return Storage.instance; } setItem(key, value) { return localStorage.setItem(key, value); } getItem(key, value) { return localStorage.getItem(key, value); }} Closure version:  function Storage() { } Storage.prototype.setItem = function (key, value) { return localStorage.setItem(key, value); } Storage.prototype.getItem = function (key) { return localStorage.getItem(key, value); } const createStorage = (function () { let instance; return function () { if (! instance) { instance = new Storage(); } return instance } })()Copy the code

How do I know if a variable is an array?

  • arr instanceof Array
  • Array.prototype.isPrototypeOf(arr)
  • Array.isArray(arr)
  • Object.prototype.toString.call(arr) === ‘[object Array]’
  • arr.constructor === Array

What are the ways in which a class array can be turned into an array?

  • [].slice.call(arguments)
  • Array.from(arguments)
  • […arguments]

Symbol.iterator

//obj is iterable because it follows the Iterator standard and contains [symbol. Iterator] methods. The function also conforms to the standard Iterator interface specification. //obj.[Symbol. Iterator]() let obj = {data: [ 'hello', 'world' ], [Symbol.iterator]() { const self = this; let index = 0; return { next() { if (index < self.data.length) { return { value: self.data[index++], done: false }; } else { return { value: undefined, done: true }; }}}; }};Copy the code

How to “deep freeze” an object in JS?

If we want to ensure that the object is deeply frozen, we must create a recursive function to freeze each attribute of the object type:

Shallow frozen

let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
Object.freeze(person); 
person.profession.name = "doctor";
console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }
Copy the code

Deep freeze

function deepFreeze(object) {
    let propNames = Object.getOwnPropertyNames(object);
    for (let name of propNames) {
        let value = object[name];
        object[name] = value && typeof value === "object" ?
            deepFreeze(value) : value;
    }
    return Object.freeze(object);
}
let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
deepFreeze(person);
person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of object
Copy the code

Handwritten ajax

  • (1) Create an XMLHttpRequest object, that is, create an asynchronous call object
  • (2) Create a new HTTP request and specify the HTTP request method, URL, and authentication information
  • (3) Set the function that responds to the change of HTTP request status
  • (4) Send HTTP requests
  • (5) Get the data returned by the asynchronous call
  • (6) Use JavaScript and DOM to achieve local refresh

The sleep function

Github.com/Advanced-Fr…

How can I tell if an object is empty?

Object.keys(obj).length === 0

Shallow clone & Deep clone Shallow copy & deep copy

Shallow cloning:

function shallowClone(obj) {
  let cloneObj = {};
  for (let i in obj) {
    cloneObj[i] = obj[i];
  }
  return cloneObj;
}
Copy the code

A deep clone

  • Consider base types
  • Reference types
    • RegExp, Date, and functions are not JSON-safe
    • Constructor is lost, with all constructors pointing to Object
    • Breaking circular references
function deepCopy(obj) {
  if (typeof obj === 'object') { // null -> object?
    var result = obj.constructor === Array ? [] : {};
    for (var i in obj) {
      result[i] = typeof obj[i] === 'object' ? deepCopy(obj[i]) : obj[i];
    }
  } else {
    var result = obj;
  }
  return result;
}
Copy the code

Can you achieve lazy loading pictures?

Juejin. Cn/post / 684490…

Write a simple Loader

Loader is a Node module that outputs a function. This function is called when a resource needs to be converted by the Loader. Also, this function can access the Loader API through the This context provided to it. reverse-txt-loader

/ / define
module.exports = function(src) {
 // SRC is the content of the original file (abcde)
 var result = src.split(' ').reverse().join(' ');
 // Return JavaScript source code, must be String or Buffer
 return `module.exports = '${result}'`;
}
/ / use
{
test: /\.txt$/,
use: [{
'./path/reverse-txt-loader'}},Copy the code

Using ES5 to implement an inheritance?

Parasitic combinatorial inheritance inherits properties by borrowing constructors and inherits methods through a hybrid form of prototype chains.

The superclass constructor is called only once, which is more efficient. Avoid creating unnecessary, redundant attributes on suberType. prototype, while keeping the prototype chain intact.

Therefore, parasitic combinatorial inheritance is the most rational inheritance paradigm for reference types.

function SuperType(name) { this.name = name; this.colors = ['red', 'blue', 'green']; } SuperType.prototype.getName = function () { return this.name; } function SuberType(name, age) { SuperType.call(this, name); this.age = age; } // Subertype.prototype = object.create (supertype.prototype); SuberType.prototype.constructor = SuberType; SuberType.prototype.getAge = function () { return this.age; } let girl = new SuberType('Yvette', 18); girl.getName();Copy the code

How to implement promise.all?

To implement Promise.all, first we need to know what promise. all does:

  • If the argument passed in is an empty iterable, then the promise callback completes (resolve), and only then, is executed synchronously; all else is returned asynchronously.
  • If the parameters passed in do not contain any promises, an asynchronous completion is returned.
  • Promises all promises in Promises are “done” or callback done when parameters do not contain promises.
  • If one of the arguments fails, the promise object returned by promise.all fails
  • In any case, promise.all returns an array as the result of the completion state of the Promise
Promise.all = function (promises) { return new Promise((resolve, reject) => { let index = 0; let result = []; if (promises.length === 0) { resolve(result); } else { function processValue(i, data) { result[i] = data; if (++index === promises.length) { resolve(result); } } for (let i = 0; i < promises.length; Resolve (Promise [I]). Then ((data) => {processValue(I, data); }, (err) => { reject(err); return; }); }}}); }Copy the code

How to realize the Promise. Prototype. Finally?

Success or failure will always go to finally, and after finally, can continue then. And passes the value exactly as it should to the subsequent then.

Promise.prototype.finally = function (callback) {
    return this.then((value) => {
        return Promise.resolve(callback()).then(() => {
            return value;
        });
    }, (err) => {
        return Promise.resolve(callback()).then(() => {
            throw err;
        });
    });
}
Copy the code