The most detailed handwritten call and apply on the Internet

handwritten call

  • Before writing code, you must analyze what this API or keyword implements and what functions it has. If you do not understand its principles, you cannot achieve a one-to-one restoration.

call

  1. First convert the pointed target we passed in into an object
  2. Assign the function to be executed to the object
  3. Execute the upward function and pass in the parameters passed in
  • Let's look at the code below:
        Function.prototype.mycall = function(test,...arr){
    
    
            if(test ===undefined || test === null){
    
    
                test = window 
            }else{
    
    
                test = Object(test)
            }
            const specialPrototype = Symbol('特殊属性')
            test.specialPrototype = this
            let result = test.specialPrototype(...arr)
            console.log(this);
            delete test.specialPrototype
            return result
        }

apply

  • The usage of apply is the same as that of call. They both execute and change the point of this. When passing parameters to a different time, apply passes an array. Multiple actual parameters passed in by call must be separated by commas. Let’s look at the code below.
        Function.prototype.myapply = function(fn,...args){
    
    
            console.log(typeof fn);
            if(fn == undefined || fn == null){
    
    
                fn = window
            }else{
    
    
                fn = Object(fn)
            }
            const spacilprototype = Symbol('特殊的项')
            fn[spacilprototype] = this
            let res = fn[spacilprototype](...args)   
            return res
        }
  • In this way, it is possible to write an apply and call by hand. It is actually very simple. When writing the code by hand, we must first think clearly about what this keyword or the api implements, and we can restore the distribution.

Guess you like

Origin blog.csdn.net/qq_52648305/article/details/126255694