一、call的实现(apply类似)

//完成版
Function.prototype.setCall = function (obj){
var object = obj || window
let arr = [...arguments]
arr.splice(0,1)
object.func = this // 将函数变成对象的内部属性
object.func(...arr) // 指定函数 并传入参数
delete object.func // 删除函数,当做什么都没发生~
}
// test:
var foo = {
value: 1
};
function show(a,b) {
console.log(this.value);
console.log(a+b)
};
show.setCall(foo,2,4)

二、bind的实现

//完成版
Function.prototype.setBind = function (obj){
var _this = this
return function (){
_this.apply(obj,arguments)
}
}

//test
var obj = {
name: 1,
getName: function(){
console.log(this.name)
}
};

var func = function(){
console.log(this.name);
}.bind(obj);

func(); // 1

 

长风破浪会有时,直挂云帆济沧海