当前位置:网站首页>关于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);
边栏推荐
- Kotlin Algorithm Getting Started with Rabbit Number Optimization and Expansion
- C Primer Plus(6) 中文版 第1章 初识C语言 1.1 C语言的起源 1.2 选择C语言的理由 1.3 C语言的应用范围
- for循环和单击相应函数的执行顺序问题
- [wxGlade learning] wxGlade environment configuration
- STM32之串口传输结构体
- MATLAB实战Sobel边缘检测(Edge Detection)
- Song of the Cactus - Massive Rapid Expansion (1)
- WiFi cfg80211
- 借问变量何处存,牧童笑称用指针,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang类型指针(Pointer)的使用EP05
- MySql的索引
猜你喜欢

企业服务器主机加固现状分析

Alibaba Sentinel - Slot chain解析

基础SQL——DDL

向日葵安装教程--向日葵远程桌面控制

Detailed Explanation of the Level 5 Test Center of the Chinese Institute of Electronics (1)-string type string

Unity3D——自定义类的Inspector面板的修改

机器学习(三)多项式回归

SDUT 2877:angry_birds_again_and_again

go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...

基于C#通过PLCSIM ADV仿真软件实现与西门子1500PLC的S7通信方法演示
随机推荐
jenkins简单使用
flex布局回顾
Nuget找不到包的问题处理
Song of the Cactus - Massive Rapid Expansion (1)
研发了 5 年的时序数据库,到底要解决什么问题?
通过Xshell连接Vagrant创建的虚拟机
What should I do if the mysql data query causes the cup to be full because the query time span is too large
轻量级网络(一):MobileNet V1,V2, V3系列
C语言操作符详解
观察表情和面部,会发现他有焦虑和失眠的痕迹
Filesystem Hierarchy Standard
The no-code platform helps Zhongshan Hospital build an "intelligent management system" to realize smart medical care
Birth of the Go language
C Primer Plus(6) 中文版 第1章 初识C语言 1.1 C语言的起源 1.2 选择C语言的理由 1.3 C语言的应用范围
Audio and video + AI, Zhongguancun Kejin helps a bank explore a new development path | Case study
无代码平台助力中山医院搭建“智慧化管理体系”,实现智慧医疗
基础SQL——DDL
SDUT 2877: angry_birds_again_and_again
For the first time, I suspect that there is a bug in selenium4 because the iframe element is not found?
4.1ROS运行管理/launch文件