当前位置:网站首页>关于ts中的指针问题call,bind, apply
关于ts中的指针问题call,bind, apply
2022-08-11 08:52:00 【MioeC】
相同
- 都可以应用于改变this的指向问题
不同
- call 传入…args
- apply 传入数组
- bind 传入…args
实现方法
call
- 原理主要是将方法复制给调用的this,再进行删除
- 代码
function dmCall(context: any) {
const fn = Symbol();
context[fn] = this;
const args = [...arguments].slice(1);
let result = context[fn](...args);
return result;
}
apply
与call一样, 只是将参数改成了数组
function dmApply(context: any, args?: any[]) {
const fn = Symbol();
context[fn] = this;
let result;
if( args === null || args === undefined) {
result = context[fn](args);
} else if (typeof args === 'object') {
console.log(...args)
result = context[fn](...args);
}
delete context[fn];
return result;
}
bind
- 比较复杂,需要新建一个函数返回,其中需要用到apply
- 原理就是,创建一个方法,将参数放入,返回该函数
function myBind(context) {
const fn = Symbol();
context[fn] = this;
const self = context;
const args = [...arguments].slice(1);
function bind() {
const res = [...arguments, ...args];
return context[fn].apply(self, res);
}
return bind;
}
Function.prototype.myBind = myBind
math1.add.myBind(a, 10)(1);
边栏推荐
- excel 透视表 值显示内容 不显示计数
- Detailed Explanation of the Level 5 Test Center of the Chinese Institute of Electronics (1)-string type string
- go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...
- 《价值》读书与投资
- Has legal counsel become a tasteless product of law firms?
- 万字长文带你了解多态的底层原理,这一篇就够了
- 《剑指offer》题解——week3(持续更新)
- 轻量级网络(一):MobileNet V1,V2, V3系列
- magical_spider远程采集方案
- C语言操作符详解
猜你喜欢
笔试题大疆08.07
magical_spider远程采集方案
Contrastive Learning Series (3)-----SimCLR
Redis 只会用缓存?20种妙用让同事直呼牛X(荣耀典藏版)
Unity3D - modification of the Inspector panel of the custom class
The no-code platform helps Zhongshan Hospital build an "intelligent management system" to realize smart medical care
机器学习(三)多项式回归
Detailed Explanation of the Level 5 Test Center of the Chinese Institute of Electronics (1)-string type string
Creo9.0 特征的成组
新一代开源免费的轻量级 SSH 终端,非常炫酷好用!
随机推荐
picker选择器出现object解决办法
Kotlin算法入门兔子数量优化及拓展
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
gRPC系列(四) 框架如何赋能分布式系统
通过Xshell连接Vagrant创建的虚拟机
C Primer Plus(6) 中文版 第1章 初识C语言 1.7 使用C语言的7个步骤
仙人掌之歌——大规模高速扩张(1)
Filesystem Hierarchy Standard
Creo9.0 特征的成组
优炫数据库支持多列分区吗?
magical_spider远程采集方案
轻量级网络(一):MobileNet V1,V2, V3系列
2022-08-09 顾宇佳 学习笔记
专题讲座8 字符串(一) 学习心得
dsu on tree(树上启发式合并)学习笔记
基于hydra库实现yaml配置文件的读取(支持命令行参数)
js将table生成excel文件并去除表格中的多余tr(js去除表格中空的tr标签)
无代码平台助力中山医院搭建“智慧化管理体系”,实现智慧医疗
Nuget找不到包的问题处理
[UEFI]EFI_DEVICE_PATH_PROTOCOL 结构体初始化的一个例子