您现在的位置是:首页 > Javascript
当前栏目
JavaScript深入之手写call、apply、bind
2023-02-18 16:30:12 时间
模拟实现call
- 将函数设为对象的属性
- 执行该函数
- 删除该函数
Function.prototype.myCall = function(context = window, ...args) {
if(this === Function.prototype) {
return undefined
}
context = context || window
const fn = Symbol()
context[fn] = this
const result = context[fn](...args)
delete context[fn]
return result
}
模拟实现apply
- 与call方法类似,参数为数组
Function.prototype.myApply = function(context = window, args) {
if(this === Function.prototype) {
return undefined
}
const fn = Symbol()
context[fn] = this
let result
if(Array.isArray(args)) {
result = context[fn](args)
} else {
result = context[fn]
}
delete context[fn]
return result
}
模拟实现bind
- 返回一个新函数
- 新函数this指向bind的第一个参数
- 其余参数作为新函数的参数传入
Function.prototype.myBind = function(context = window, ...args1) {
if(this === Function.prototype) {
throw new TypeError('Error')
}
const _this = this
return function F(...args2) {
if(this instanceof F) {
return new _this(...args1, ...args2)
}
return _this.apply(context, args1.concat(args2))
}
}
相关文章
- 分享一个Javascript通过正则表达式验证E-Mail地址有效性的函数
- 分享一个用jQuery实现自动检测并设置浏览器编码的实例
- Spring Boot中的Freemarker模版引擎引用css和js的正确姿势
- Node.js解压版的环境配置及相关常用命令
- JSP学习笔记(6)—— 自定义MVC框架
- JSP学习笔记(5)——Servlet、监听器、过滤器、MVC模式介绍
- Jsp学习笔记(4)——分页查询
- JSP学习笔记(3)——JSTL 标签库
- JSP学习笔记(1)——Jsp指令、动作元素和内置对象
- echarts map地图中绘制浙江省市区县乡镇多级联动边界下钻的最新geojson数据文件获取和更新
- ArcGIS QGIS学习一:打开shp、geojson地图变形变扁问题(附最新坐标边界下载全国省市区县乡镇)
- 从区划边界geojson中查询经纬度坐标对应的省市区县乡镇名称,开源Java工具,内存占用低、高性能
- 全国省市区县和乡镇街道行政区划矢量边界坐标经纬度地图最新数据免费下载 支持shp geojson json sql格式
- 几行代码把Chrome搞崩溃之:HTML5 MP3录音由ScriptProcessorNode升级成AudioWorkletNode采坑记
- JavaScript ES6 Promise对象
- Web前端——JavaScript扩展补充
- Web前端——表单提交和Js添加选项
- Web前端——JavaScript练习
- Web前端——JavaScript笔记
- 从高德采集最新的省市区三级坐标和行政区域边界,用js在浏览器中运行