js new call apply bind的底层实现
new
1. 以 Object.protoype 为原型创建一个新对象
2. 以新对象为 this,执行函数的 [[call]]
3. 如果 [[call]] 的返回值是对象,那么,返回这个对象,否则返回第一步创建的新对象
1 2 3 4 5 | function myNew(fn, ...args) { const obj = Object.create(fn.prototype); const ret = fn.call(obj, ...args); return ret instanceof Object ? ret : obj; } |
call
实际上就是把方法挂在对象上,执行然后删除
1 2 3 4 5 6 7 8 9 10 | Function.prototype.myCall = function (context, ...args) { if ( typeof this !== 'function' ) { throw new TypeError( 'this is not a function' ) } context = context || window; context.fn = this ; const ret = context.fn(...args); delete context.fn; return ret } |
例子:fn.call(null,10,20,30);
apply
原理和call一样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Function.prototype.myApply = function (context, arg) { if ( typeof this !== 'function' ) { throw new TypeError( 'this is not a function' ) } context = context || window; context.fn = this ; let ret; if (arg) { ret = context.fn(...args); } else { ret = context.fn(); } delete context.fn; return ret } |
例子:fn.apply(null,[10,20,30]);
bind
bind原理就是封一层闭包
1 2 3 4 5 6 7 8 9 10 | function .prototype.myBind = function (context, ...bindArgs) { if ( typeof this !== 'function' ) { throw new TypeError( 'this is not a function' ); } const _this = this ; return function Fn(...execArgs) { const args = bindArgs.concat(execArgs); return _this.call( this instanceof Fn ? this : context, ...args); } } |
例子:fn.bind(opp,10,20)
可以形象的描述为:超人有飞的能力,我借用下超人会飞的能力,我也会飞了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2020-07-22 小程序弹出层覆盖不了canvas