|
首先,三者第一個(gè)參數(shù)都為this指向 區(qū)別bind返回的是一個(gè)函數(shù)體 call和apply會直接執(zhí)行,但是call參數(shù)需要一個(gè)一個(gè)進(jìn)行傳遞,apply的第二個(gè)參數(shù)是一個(gè)數(shù)組 實(shí)現(xiàn)bind簡單實(shí)現(xiàn)考慮到函數(shù)柯里化的實(shí)現(xiàn)Function.prototype.myBind = function(context){ // 使用閉包存下初始參數(shù)
var args = Array.prototype.slice.call(arguments, 1),
self = this; return function() { // 再次調(diào)用時(shí)
var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return self.apply(context,finalArgs);
};
};考慮構(gòu)造函數(shù)的實(shí)現(xiàn)Function.prototype.myBind = function(context){ // 判斷是否為函數(shù)
if(typeof this !== 'function') { throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
} var args = Array.prototype.slice(arguments, 1);
self = this;
bound = function() { var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); // 判斷this,如果是,則傳遞this即實(shí)例化的對象。
return self.apply((this instanceof F ? this : context), finalArgs);
}; // 處理原型鏈
let F = function(){};
F.prototype = self.prototype;
bound.prototype = new F();
retrun bound;
};call思路 實(shí)現(xiàn)Function.Prototype.myCall = function(context) { // this 參數(shù)可以傳 null,當(dāng)為 null 的時(shí)候,視為指向 window
var context = context || window;
context.fn = this; // 對參數(shù)進(jìn)行處理
var args = []; for(var i = 1, len = arguments.length; i < len; i++) {
args.push(arguments[i]);
}
let result = arguments.length>0 ? context.fn(...args) : context.fn(); delete context.fn; return result;
}apply |
|
|