call
call的理解:
call() 方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数
call方法的调用的整个过程:
当实例(函数)通过原型链的查找机制,找到function.prototype上的call方法,function call() {[ native code ]}
1、首先把药操作的函数中的this关键字变为call方法第一个传递的实参
2、把call方法第二个及之后的实参获取到
3、把药操作的函数执行,并且把第二个以后传递进来的实参传递给函数
然后面试中会经常问到自己怎么模拟手写一个call函数,以下是我看别人的博客总结的一些:
第一种:
Function.prototype.call2 = function(context) {
const context = context || window
context.fn = this
let args = []
for(let i = 1, len = arguments.length;i < len;i++) {
args.push('arguments[' + i + ']')
}
const result = eval('context.fn(' + args +')')
delete context.fn
return result
}
第二种:
Function.prototype.myCall = function(context = window, ...args) {
// context是指传入的red
let func = this;
let fn = Symbol("fn");
context[fn] = func;
let res = context[fn](...args);//重点代码,利用this指向,相当于context.caller(...args)
// console.log('****',...args)
delete context[fn];
return res;
}
apply
apply的也是为了改变this的指向,但它和call的区别是传入的参数的不同
Function.prototype.apply = function (context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
}
delete context.fn
return result;
}
bind
bind( )方法创建一个新的函数,在bind( )被调用时,这个新函数的this被指定为bind()被调查时,这个新函数的this被指定为bind()的第一个参数,而其余参数作为新函数的参数,供调用时使用。
// 第四版
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}