Advantages and disadvantages of several inheritance analyses

Prototype chain inheritance
            function Parent () {
                this.names = ["Lick the dog's tears."];
            }
            
            function Child () {
            
            }
            
            Child.prototype = new Parent();
            
            let child1 = new Child();
Copy the code

Disadvantage 1: Cannot pass parameters to Parent.

    child1.names.push(1)
    let child2=new Child()
    console.log(child2.names) // [" Lick dog's tears ",1]
Copy the code

Disadvantage 2: Multiple instances can modify operations on reference types

The call to inherit
            function Parent () {
                this.names = "Lick the dog's tears.";
            }
            
            Parent.prototype.getName=() = >{}
            
            function Child () {
                Parent.call(this.'Can pass parameters')}let child1 = new Child();
Copy the code

Advantages: Can transfer parameters. Disadvantages: Child1 does not have the same methods as the Parent prototype

Combination of inheritance
            function Parent () {
                this.names = "Lick the dog's tears.";
            }
            
            Parent.prototype.getName=() = >{}
            
            function Child () {
                Parent.call(this.'Can pass parameters')
            }
            
            Child.prototype=new Parent()
            
            let child1 = new Child();
Copy the code

Advantages: can pass can get the parent prototype above the method. Prototype =new Parent(); prototype=new Parent();

Parasitic inheritance
     function createP(original) {
         Clone. Prototype ={name: 'clone'}
        var clone = Object.create(original); 
        clone.getName  = function () {
          // Enhance objects in some way
          console.log(this.name)
        };
        return clone; 
      }
    
     var parent = { name: 'Lick the dog's tears' };
     var child = createP(parent);
Copy the code

Disadvantage 1: Cannot pass parameters to Parent. Disadvantage 2: Multiple instances can modify operations on reference types

Parasitic combinatorial inheritance
            function Parent () {
                this.names = ["Lick the dog's tears."];
            }
            
            Parent.prototype.getName=() = >{}
            
            function Child () {
                Parent.call(this.'Can pass parameters')
            }
            
            Child.prototype=Object.create(Parent.prototype)
            Child.prototype.fn=() = >{}
            
            let child1 = new Child();
Copy the code

All the above shortcomings have been optimized

Call, apply, bind implementation

Call can support multiple arguments

Usage: fn1.mycall1 (‘ point ‘,’ parameter 1′,’ parameter 2′)

    Function.prototype.myCall1 = function (context,... arg) {
        Context points to window if no object is passed or if the value passed is empty
        context = context || window;
        let fn = mySymbol();
        context[fn] = this; // Add a method to the context pointing to this
        // The first parameter, this, is passed to the other fn functions
        constresult = context[fn](... arg);/ / execution fn
        delete context[fn]; // Delete method
        // Returns the return value of the function call
        return result;
      };

Copy the code

Context [fn] (); context[fn] (); context[fn] (); context[fn]; This in here refers to the context, because the context is calling it.

apply

Usage: fn.myApply(‘ point to ‘,[‘ parameter 1′,’ parameter 2′]), basically the same as call.

     Function.prototype.myApply = function (context, args) {
        context = context || window;
        args = args ? args : [];
        const fn = Symbol(a); context[fn] =this;
        constresult = context[fn](... args);delete context[fn];
        return result;
      };
Copy the code
bind

Bind is necessary to analyze a wave, most people really don’t understand. Usage: fn.mybind (‘ point to ‘,’ argument 1′)(‘ argument 2’).

    Function.prototype.myBind = function (context) {
        if (typeof this! = ='function') {
          throw new Error('Please bind a function');
        }

        var self = this;
        var args = Array.prototype.slice.call(arguments.1);

        var fBound = function () {
          var funArgs = Array.prototype.slice.call(arguments);
          return self.apply(
            this instanceof fNOP ? this : context,
            args.concat(funArgs)
          );
        };
        var fNOP = function () {};
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
      };

Copy the code

Why do this line of judgment this instanceof fNOP? This: context, when used as a constructor, does not change the reference to this. This in fBound refers to a. this instanceof fNOP ===true

    let A=Animal.bind(Cat,name)
    let a=new A()
Copy the code

Why write the following lines of code? When other methods exist on the Animal prototype, A can’t get them.

        var fNOP = function () {};
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
Copy the code

Fbound. prototype=this.prototype If fbound. prototype=this.prototype, the pointer to fbound. prototype and this.prototype point to the same memory space, and the fbound. prototype changes will affect this.prototype

The implementation principle of new

  1. Create an empty object
  2. The connection of this new object prototype
  3. Execute constructor methods, properties and methods that point to the created object
  4. If no other object is returned from the constructor, return this, the new object of the created one; otherwise, return the object returned from the constructor.
        function _new(){
            let targetObj={}
            let [constructor.args] = [...arguments]
            targetObj.__proto__=constructor.prototype
            let result =constructor.apply(targetObj,args)
            if(result&&(typeof (result)==='object'||typeof (result)==='function')) {return result
            }

            return targetObj
        }
Copy the code

compose

The essence of the redux applyMiddleware source code is also the compose method, which strings middleware together. You can have a look at redux source code, written really awesome. Compose comes with the input function.

        function middleware1(x){
            return x+1
        }
        function middleware2(x){
            return x+1
        }
        function middleware3(x){
            return x+1
        }
        function middleware4(x){
            return x+1
        }
        function compose(. funcs) {
            return arg= > funcs.reduceRight((composed, f) = > f(composed), arg);
        }
        compose(middleware1,middleware2,middleware3,middleware4)(0)
Copy the code

Deep copy

If the WeakMap version is not used, circular references will loop forever and cause memory leaks

       function deepClone1(obj){
            if(typeof obj==='object'&&obj! = =null) {let obj1=Array.isArray(obj) ? [] : {}
                for (let key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        obj1[key] = deepClone(obj[key]) // Recursive copy}}return obj1
            }
            return obj
        }
        let test={name:'aa'.age:18}
        test.a=test
        let test1=deepClone1(test) // An error will be reported, memory overflow
Copy the code

By referring to WeakMap, the above overflow problem can be handled, and both Map and WeakMap can handle it

     function deepClone2(obj, hash = new WeakMap(a)){
            if(typeof obj==='object'&&obj! = =null) {if (hash.has(obj)) {
                    return hash.get(obj);
                }
                let obj1=Array.isArray(obj) ? [] : {}
                hash.set(obj, obj1);
                for (let key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        obj1[key] = deepClone2(obj[key],hash) 
                    }
                }
                return obj1
            }
            return obj
        }
Copy the code

An array of flat

   [1.2.3[4.5[6.7]]].flat(Infinity)  //[1, 2, 3, 4, 5, 6, 7]
Copy the code
    function flatter(arr) {
            if(! arr.length)return;
            return arr.reduce(
              (pre, next) = >
                Array.isArray(next) ? [...pre, ...flatter(next)] : [...pre, next],
              []
            );
        }
Copy the code

The function is currified

Fn. length specifies the addFn parameter length, which is 3 because of a,b, and c

  let curry = (fn, ... args) = > args.length < fn.length ? (.arguments) = >curry(fn, ... args, ... arguments) : fn(... args);function addFn(a, b, c) {
      return a + b + c;
  }
  var add = curry(addFn);
  
  add(1.2.3) / / 6
  add(1.2) (3) / / 6
  add(1) (2) (3) / / 6
Copy the code

AsyncSeriesWaterfallHook in Webpack

This is an asynchronous serial hook, and the next task gets the return value of the previous task. Below is the usage. At the heart of the Webpack event flow is tapable, the nine hooks on tapables that control the cascading execution of plugins

	{ AsyncSeriesWaterfallHook } = require('tapable')
	let myAsyncSeriesWaterfallHook=new AsyncSeriesWaterfallHook(['name'])
	myAsyncSeriesWaterfallHook.tapAsync('1'.(name,cb) = >{
		setTimeout(() = >{
			console.log('1',name)
			cb(null.'aa')},1000)}) myAsyncSeriesWaterfallHook. TapAsync ('2'.(name,cb) = >{
		setTimeout(() = >{
			console.log('3',name)
			cb(null.'bb')},1000)}) myAsyncSeriesWaterfallHook. TapAsync ('3'.(name,cb) = >{
		setTimeout(() = >{
			console.log('3',name)
			cb(null.'cc')},1000)}) myAsyncSeriesWaterfallHook. CallAsync ('yang'.() = >{
		console.log('end')})// 1 yang
        // 2 aa
        // 3 bb
        // end   
Copy the code

No asynchronous serial hooks implemented with async await. Clever use of next.

    
class AsyncSeriesWaterfallHook{
    constructor() {
        this.hooks = [];
    }
    tapAsync () {
        this.hooks.push(arguments[arguments.length-1]);
    }
    callAsync () {
        let args = Array.from(arguments); // Convert the passed parameters to an array
        let done = args.pop(); // Retrieves the last item of the array, the successful callback
        let index = 0;
        let _this = this;
        function next(err, data) {
            if(index>=_this.hooks.length) return done();
            if (err) return done(err);
            let fn = _this.hooks[index++];
            if (index == 1) { fn(... args, next) }else {
                fn(data, next)
            }
        }
        next()
    }
}
Copy the code

ES6 class

Juejin. Cn/post / 702429…

Map Set

Juejin. Cn/post / 702540…

Promise

Juejin. Cn/post / 702689…

async await

Juejin. Cn/post / 702910…

conclusion

She stood stunned, and then went upstairs, I returned to the dormitory not a moment later received her message, wrote a lot of… It was the first time in my life that I confessed my love to a girl. It was also the first time that I felt the taste of heartache. I didn’t know how to reply to her, so I looked over our chat records for a whole night… Behind every day for a period of time I had to go, had not interest in anything, I don’t have to help her to take breakfast, my relationship with her also becomes a very delicate, I afraid she see me, every time in class I will find a far away from her position, the two of us also did not have any news, but I still want to her… Hero alliance dominated our university for four years, Internet cafes, dormitory basic is the game, when the school was organized hero league game, every professional sent a team to play the game, have come from ai, drill a me to become a member of the entry, as the game’s victory, we are classmates watches, many students will take the initiative and greet with me, chat, About me to play games, that was the first time I felt THAT I was at least not good for nothing, we came to the 4 strong, the night before the game, the students have issued a blessing to us, she also gave me a separate message in the evening, said some refurefuting words, I suppressed the excitement of the heart replied: ok. In the final four, I sacrificed my Wayne in 3000 games. In the early stage of the team battle, I ended the end of the team battle with my various flirty moves and a wave of “blow it Q”. That night, I became the hot topic of discussion in the school’s post bar… (To be continued)