call,apply,bind都属于Function对象的原型方法。
call和apply方法都会根据指定的this对象值来调用函数。
1、call方法
Function.prototype._call = function(obj){
let that = this;
if(typeof that != "function")
{
console.log("not function");
return;
}
let arr = Array.from(arguments).slice(1),
res = null;
obj = obj || window;
obj.fn = this;//this指向调用call的
//调用函数。
res = obj.fn(...arr);
delete obj.fn;
return res;
}
let obj = {
name: 'obj'
}
var name = 'window'
function f(a,b) {
console.log( a+b )
}
f._call(obj,1,2);
2、apply方法
apply方法以数组的形式接收其他参数
实现过程:
1) 判断第二个参数是不是数组
2)将方法挂载到obj属性上
3)调用该方法
4)删除新增的obj属性
Function.prototype._apply = function(obj)
{
let that = this;
let res = null;
let arr = arguments[1];
if(typeof that != "function")
{
console.log("不是函数");
return;
}
obj = obj || window;
obj.fn = this;
if(arr.length != 0)
{
res = obj.fn(...arr);
}else{
res = obj.fn();
}
delete obj.fn;
return res;
}
f._apply(obj,[1,2]);
3、bind方法
bind方法不会直接调用函数,返回值是一个新的函数实例。
Function.prototype._bind = function(obj){
let that = this;
if(typeof this != "function")
{
console.log("not function");
return;
}
return ()=>{
let arr = [...arguments].splice(1);
let res = null;
obj = obj || window;
obj.fn = this;
res = obj.fn(...arr);
delete obj.fn;
return res;
}
}
f._bind(obj,1,2)();