bind/ call实现方法(javaScript)
call方法实现
```js
// 用于获取对象中的值
function gtname() {
console.log(this.name);
}
// 对象
let obj = {
name: "kyle",
num: 0,
};
// 实现方法
Function.prototype.myCall = function (obj, ...args) {
let self = this;
obj.$$$fn = self;
delete obj.$$$fn(...args);
};
// 结果
gtname.myCall(obj);
```
bind方法实现:利用闭包实现
```js
Function.prototype.myBind = function (obj) {
let self = this;
let $obj = {
...obj,
};
$obj.$fn = self;
return function () {
$obj.$fn();
};
};
let res = addNum.myBind(obj);
function addNum() {
this.num++;
}
// 结果
setInterval(res, 200);
```

浙公网安备 33010602011771号