call,apply,bind实现

call的实现原理:在方法调用模式下,this 总是指向调用它所在方法的对象,this 的指向与所在方法的调用位置有关,而与方法的声明位置无关(箭头函数特殊)

利用 this 的机制来实现 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的实现:

 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实现:封装了 call 的方法改变了 this 的指向并返回一个新的函数

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 }

猜你喜欢

转载自www.cnblogs.com/vicky24k/p/11888962.html