call, apply, bind achieve

The principle of call: In the method call mode, this always point it at the object method call, this the call point to the location and method where relevant, irrespective of the position statement of the method (special arrow function)

The use of  this mechanisms to achieve call

 1 Function.prototype.mycall = function(thisArg) {
 2     if(typeof this !== 'function') {
 3         throw TypeError(`${this} is not a function`);
 4     }
 5     const args = [...arguments].slice(1);
 6     thisArg = thisArg || window;
 7     thisArg.fn = this;
 8     const result = thisArg.fn(...args);
 9     delete thisArg.fn;
10     return result;
11 }

 

apply realization:

 1 Function.prototype.myapply = function(thisArg) {
 2     if(typeof this !== 'function') {
 3         throw TypeError(`${this} is not a function`);
 4     }
 5     thisArg = thisArg || window;
 6     const args = arguments[1];
 7     thisArg.fn = this;
 8     const result = thisArg.fn(...args);
 9     delete thisArg.fn;
10     return result;
11 }

 

bind achieved: encapsulate  call the method of changing the  this directivity function and returns a new

1 Function.prototype.mybind = function(fun) {
2     if(typeof this !== 'function') {
3         throw TypeError('Bind must be called on a function')
4     }
5     var self = this;
6     return function () {
7         self.apply(fun, arguments);
8     }
9 }

 

Guess you like

Origin www.cnblogs.com/vicky24k/p/11888962.html