手动实现一个call bind

2023-05-07,

一、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

手动实现一个call bind的相关教程结束。

《手动实现一个call bind.doc》

下载本文的Word格式文档,以方便收藏与打印。