1, the apply

code

Function.prototype.myApply = function () {
    let thisObj = arguments[0] || window;
    let args = arguments[1];
    thisObj.fn = this;
    letres = thisObj.fn(... args); delete thisObj.fn;return res;
}
Copy the code

test:

2, call

code

Function.prototype.myCall = function () {
    let thisObj = arguments[0] || window;
    let args = [...arguments].slice(1);
    thisObj.fn = this;
    letres = thisObj.fn(... args); delete thisObj.fn;return res;
}
Copy the code

test:

3, the bind

code:

Function.prototype.myBind = function () {
   let thisObj = arguments[0] || window;
   let fn = this;
   let args = [...arguments].slice(1);
   return function F () {
       if (this instanceof F) {
           returnnew fn(... args, ... arguments) }else {
           returnfn.apply(thisObj, args.concat([...arguments])); }}}Copy the code

test

4, throttling

code

function throttle (fn, time) {
    let startTime = +new Date();
    return function F () {
        let lastTime = +new Date();
        if(lastTime - startTime >= time) { fn.apply(this, [...arguments]); startTime = lastTime; }}}Copy the code

test

5, if you

code

function antiShake (fn, time, immediate) {
    let time = null;
    return function F () {
        if (immediate) {
           fn.apply(this, [...arguments]);
        }
        if (time) {
            clearInterval(time);
        }
        setInterval(function() { fn.apply(this, [...arguments]); }, time); }}Copy the code

6, inheritance

code

 function Animal(name) {
     this.name = name;
 }
 Animal.prototype.say = function () {
     console.log('my name is:' + this.name);
 }
 function Dog(name, age) {
     Animal.apply(this, [name]);
     this.age = age;
 }
 Dog.prototype = Object.create(Animal.prototype, {
     constructor: {
         value: Dog,
         enumable: false,
         writable: true,
         configurable: true}}); var a = new Dog('xiaowang'1),Copy the code

code

7, instanceof

code

function myInstanceof(left, right) {
    var r = right.prototype;
    left = left.__proto__;
    while(true) {
        if (left === null) {
            return false;
        } else if (left === r) {
            return true; } left = left.__proto__; }}Copy the code

test

8, the new

code

  functionmyNew(fn, ... args) {let obj = {};
      obj.__proto__ = fn.prototype;
      var res = fn.apply(obj, args);
      return res instanceof Object ? res : obj;
  }
Copy the code

test

9. Corrification

code

functioncurrying (fn, ... args) {if (fn.length <= args.length) {
        returnfn(... args); }return function F() {
        returncurrying(fn, ... args, ... arguments); }}Copy the code

test

10. Deep copy

Method 1

code

JSON.parse(JSON.stringify(obj))
Copy the code

test

Disadvantages:

  1. Function cannot be serialized
  2. Loop nesting cannot be resolved
  3. 6. The underpay cannot be serialized
  4. Symbol cannot be serialized

Method # # 2

code

function messageChannelClone(obj) {
    return new Promise((resolve, reject) => {
        const {port1, port2} = new MessageChannel();
        port2.onmessage = res => resolve(res.data);
        port1.postMessage(obj);
    })
}
var b = {
    info: {
        name: 'jin'
    }
}
messageChannelClone(b).then(res=>{
    console.log(res);
})
Copy the code

test

Disadvantages:

  1. Function cannot be serialized
  2. Symbol cannot be serialized

Method 3 uses the — Lodash library

Method 4 simple simulation implementation

code

function clone(obj) {
    let res;
    if (obj && obj instanceof Object) {
        res = Array.isArray(obj) ? [] : {};
        for (let item in obj) {
            res[i] = obj[item] instanceof Object ? clone(obj[item]) : obj[item]; }}else {
        res = obj;
    }
    return res;
}
Copy the code

11, JSON parse

Method 1

code

var a = '{name: "jiweijin"}'
eval('(' + a + ') ')
Copy the code

Method 2

var a = '{name: "jiweijin"}'
new Function('return ' + a)()
Copy the code

12, JSON. Stringify

code

function jsonStringify(obj) {
    let type = typeof obj;
    if (type! = ="object") {
        if (/string|undefined|function/.test(type)) {
            obj = '"' + obj + '"';
        }
        return String(obj);
    } else {
        let json = []
        let arr = Array.isArray(obj)
        for (let k in obj) {
            let v = obj[k];
            let type = typeof v;
            if (/string|undefined|function/.test(type)) {
                v = '"' + v + '"';
            } else if (type= = ="object") {
                v = jsonStringify(v);
            }
            json.push((arr ? "" : '"' + k + '" :) + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}")}}Copy the code

13, ajax

code

Simple version of

function myHttp(opt) {
  let url = opt.url || ' ';
  let method = opt.method || 'POST';
  let data = opt.data || {};
  let http = new XMLHttpRequest();
  if (method.toUpperCase === 'GET') {
    var dataStr = ' ';
    for (let item in data) {
        dataStr += item + '=' + data[item];
    }
    url += '? ' + dataStr;
    http.open(method, url);
    http.send(null)
  } else {
     http.open(method, url)
     http.send(data)
  }
  http.onreadystatechange = function () {
      if (http.readystate === 4 && http.status === 200) {
          opt.success(http.responseText)
      }
  }
}

Copy the code

14, promise

code

/** * 1. When a new Promise is passed, an executor executor is passed and the executor executes immediately. 3. Promise can only be changed from pending to rejected, or from pending to depressing * 4. Once the state of promise is confirmed, * 5. Promise is always therethenMethod,thenOnFulfilled, * and onRejected * 6. This is a big pity. If the callthen", the promise will be fulfilled, and the promise value will be passed in as parameter. * If the promise has failed, then execute onRejected and pass in the reason why the promise failed. * If the state of the promise is pending, the ondepressing and onRejected functions need to be stored. After the state is determined, the corresponding functions will be executed successively (release and subscribe) * 7.thenOnFulfilled and onRejected can default * 8. Promise can be fulfilledthenMany times, I promisedthenMethod returns a promise * 9. IfthenIt returns a result, and that result is passed as an argument to the next onethenThis is a big pity * 10. IfthenThrows an exception, which is passed to the next one as an argumentthen(onRejected) * 11. IfthenReturn is a promise, then need to wait for this promise, then will wait for this promise to finish, if the promise is successful, * will go nextthenIf you fail, move on to the next onethenError */ const PENDING ='pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise(executor) {
    letself = this; self.status = PENDING; self.onFulfilled = []; // Successful callback self.onRejected = []; // Failed callback //PromiseA+ 2.1function resolve(value) {
        if(self.status === PENDING) { self.status = FULFILLED; self.value = value; self.onFulfilled.forEach(fn => fn()); / / PromiseA + 2.2.6.1}}function reject(reason) {
        if(self.status === PENDING) { self.status = REJECTED; self.reason = reason; self.onRejected.forEach(fn => fn()); //PromiseA+ 2.2.6.2}} try {executor(resolve, reject); } catch (e) { reject(e); } } Promise.prototype.then =function(onFulfilled, //PromiseA+ 2.2.1 /PromiseA+ 2.2.5/2.2.7.3/2.2.7.4 ondepressing = typeof onFulfilled ==='function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
    letself = this; / / PromiseA + 2.2.7let promise2 = new Promise((resolve, reject) => {
        if(self.status === depressing) {//PromiseA+ 2.2.2 //PromiseA+ 2.2.4 --setTimeout
            setTimeout(() => {try {//PromiseA+ 2.2.7.1letx = onFulfilled(self.value); resolvePromise(promise2, x, resolve, reject); //PromiseA+ 2.2.7.2 reject(e); }}); }else if(self.status === PromiseA) {//PromiseA+ 2.2.3setTimeout(() => {
                try {
                    letx = onRejected(self.reason); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); }}); }else if (self.status === PENDING) {
            self.onFulfilled.push(() => {
                setTimeout(() => {
                    try {
                        letx = onFulfilled(self.value); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); }}); }); self.onRejected.push(() => {setTimeout(() => {
                    try {
                        letx = onRejected(self.reason); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); }}); }); }});return promise2;
}

function resolvePromise(promise2, x, resolve, reject) {
    letself = this; / / PromiseA + 2.3.1if (promise2 === x) {
        reject(new TypeError('Chaining cycle'));
    }
    if (x && typeof x === 'object' || typeof x === 'function') {
        letused; //PromiseA+2.3.3.3.3 Only invoke try {let then = x.then;
            if (typeof then= = ='function') {/ / PromiseA + 2.3.3. Then call (x, (y) = > {/ / PromiseA + 2.3.3.1if (used) return;
                    used = true; resolvePromise(promise2, y, resolve, reject); }, (r) => {//PromiseA+2.3.3.2if (used) return;
                    used = true;
                    reject(r);
                });

            }else{/ / PromiseA + 2.3.3.4if (used) return;
                used = true; resolve(x); }} Catch (e) {//PromiseA+ 2.3.3.2if (used) return;
            used = true; reject(e); }}else{/ / PromiseA + 2.3.3.4 resolve (x); }}Copy the code