Call, apply, bind, etc
All three of these are there to change the direction of this, so it’s going to be a little bit different, so let’s look at a picture
The use of the call
1var a = {
2 des:'Lovely you'
3}
4function fn(age,name) {
5 console.log(age,name,this.des)
6}
7/ / execution
8fn.call(a,18.Alipay);
Copy the code
The execution result
Let’s mock a call
1Function.prototype.myCall = function(context) {
2 // Get the first argument, the object passed by the user
3 var context = context || window;
4 // Get the rest of the parameters except for the first object
5 var args = [...arguments].slice(1);
6 // Mount the current function on the passed object
7 context.fn = this;
8 // Execute the mounted function
9 varresult = context.fn(... args);
10 // Delete the mount object
11 delete context.fn;
12 // Returns the execution result
13 return result;
14}
Copy the code
The execution result
Look at “Call”, then look at “apply”, the principle is the same
use
1var a = {
2 des: 'Handsome You'
3}
4function fn (age, name) {
5 console.log(age, name, this.des)
6}
7The second argument to apply is an array
8fn.apply(a, [18.'WeChat'])
Copy the code
The execution result
Again, let’s emulate an implementation of Apply
1Function.prototype.myApply = function(context) {
2 // Get the first argument object
3 var context = context || window;
4 // Get the rest of the parameters except the first one
5 var args = arguments.slice(1) [0];
6 // Mount the current function to the passed object
7 context.fn = this;
8 // Execute the function
9 varresult = context.fn(... args);
10 // Delete the mount object
11 delete context.fn;
12 // Return the result
13 return result;
14}
Copy the code
The execution result
The use of the bind
1let a = {
2 des: 'Perfect you'
3}
4function fn (age, name) {
5 console.log(age,name,this.des)
6}
7⚠️bind returns a function, so you need to add () to it
8fn.bind(a,18.Yu 'e Bao) ();
Copy the code
The execution result
Again, let’s copy a bind implementation
1Function.prototype.Mybind = function (context) {
2 // First you need to check whether the call is correct
3 if(typeof this! = ='function') {
4 throw new TypeError('Error');
5 }
6 // Store the current function
7 var _this = this;
8 // Get parameters
9 var args = [...arguments].slice(1);
10 // Return a function
11 return function F () {
12 // Need to consider whether the new case
13 if(this instanceof F) {
14 return new_this(... args,... arguments)
15 }
16 // Otherwise, apply returns the result
17 return_this.apply(context,args.concat(... arguments));
18 }
19}
Copy the code
The execution result
~ ~ share a little bit every day and make progress with you