call
三个要素:
1.将函数设置为对象的属性
2.执行该函数,并且代入参数
3.删除该函数
实现:
Function.prototype.call2=function(obj,...ags){
const context=obj||window;//有可能为null
context.fn=this;//赋值
const data= context.fn(...ags)//返回值的情况
delete context.fn;//删除
return data;//返回函数返回值
}
const obj={
a:999
}
function test(a,b){
console.log(this.a,a,b)
return "我是返回值"
}
test.call2(obj,10,9)//测试正常使用
test.call2(null,10,9)//测试为null的情况
console.log(test.call2(null,10,9))//测试为有返回值的情况
apply
Function.prototype.apply2 = function (obj, arr) {
const context = obj || window; //有可能为null
context.fn = this; //赋值
const data = Object.prototype.toString.call(arr) === "[object Array]" ? context.fn(...arr) : context.fn();
delete context.fn; //删除
return data; //返回函数返回值
};
const obj = {
a: 999,
};
function test(a, b) {
console.log(this.a, a, b);
return "我是返回值";
}
test.apply2(obj, [10, 9]); //测试正常使用
test.apply2(null, [10, 9]); //测试为null的情况
console.log(test.apply2(null, [10, 9])); //测试为有返回值的情况
bind
Function.prototype.bind2=function(context,...args){
const fn=this;
context.fn=fn;
return function(){
return context.fn(...args,...arguments)
}
}