当前位置:网站首页>自定义实现JS中的bind方法
自定义实现JS中的bind方法
2022-06-22 06:51:00 【webchang】
bind方法要实现什么功能?
- bind()方法用于将函数体内的this绑定到某个对象,然后返回一个新函数。
- bind()方法的第一个参数就是所要绑定this的对象,后边可以接收更多的参数。
- bind()方法返回的新函数也可以接收参数。
方式1
function myBind(fn, newThis, ...arg1) {
return function (...arg2) {
let args = arg1.concat(arg2);
return fn.apply(newThis, args); // 注意要 return 一下,因为原来的那个函数可能有返回值
}
}
// 测试
function demo(...args) {
console.log(args);
console.log(this.color);
}
let obj = {
color: 'red'
};
let newDemo = myBind(demo, obj, 1, 2);
newDemo(5, 6);
// [1, 2, 5, 6]
// "red"
方式2
Function.prototype.myBind = function (newThis,...arg1) {
let that = this; // 这里的 this指向当前调用 myBind方法的函数
return function (...arg2) {
let args = [...arg1,...arg2];
return that.apply(newThis,args);
}
};
// 测试
function add(x, y) {
return x * this.m + y * this.n;
}
let obj2 = {
m:2,
n:3
};
let newAdd = add.myBind(obj2,5);
console.log(newAdd(2)); // 16
前端学习交流QQ群,群内学习讨论的氛围很好,大佬云集,期待您的加入:862748629 点击加入
边栏推荐
猜你喜欢

【5G NR】RRC连接重建解析
![[openairinterface5g] rrcsetuprequest for RRC NR resolution](/img/de/34e71154941f977546362f10a19929.jpg)
[openairinterface5g] rrcsetuprequest for RRC NR resolution

SQL injection vulnerability (XII) cookie injection

首次用DBeaver连接mysql报错

【5G NR】NG接口
![[5g NR] NAS connection management - cm status](/img/a3/c23958ff593f77cdc459bebc3f87d2.png)
[5g NR] NAS connection management - cm status

Databricks from open source to commercialization

Which is the best agency mode or decoration mode
![[openairinterface5g] RRC NR resolution (I)](/img/04/fec30b5c86f29d82bd7d0b13293494.jpg)
[openairinterface5g] RRC NR resolution (I)

Using Monte Carlo method to calculate pi
随机推荐
Py之scorecardpy:scorecardpy的简介、安装、使用方法之详细攻略
QT connect to Alibaba cloud using mqtt protocol
Cesium loading 3D tiles model
OpenGL - Draw Triangle
Producer and consumer issues
《数据安全实践指南》- 数据采集安全管理
【OpenAirInterface5g】RRC NR解析之RrcSetupRequest
Training penetration range 02 | 3-star VH LLL target | vulnhub range node1
[M32] single chip microcomputer SVN setting ignore file
DL and alignment of spatially resolved single cell transcriptomes with Tangram
[5g NR] ng setup of ngap protocol
The song of cactus - marching into to C live broadcast (1)
仙人掌之歌——上线运营(5)
[rust notes] 04 expression
【5G NR】UE注册管理状态
Error when connecting MySQL with dbeaver for the first time
Five common SQL interview questions
Languo technology helps the ecological prosperity of openharmony
仙人掌之歌——进军To C直播(1)
On the pit of delegatecall of solidity