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
First convert the pointed target we passed in into an object
Assign the function to be executed to the object
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 =thislet 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]=thislet 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.