手动实现一个call bind
原创
阿里CTO
©著作权
文章标签
编程
文章分类
运维
©著作权归作者所有:来自51CTO博客作者阿里CTO的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、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
长风破浪会有时,直挂云帆济沧海