当前位置:网站首页>Principle and Simulation of bind
Principle and Simulation of bind
2022-06-29 12:58:00 【Henry_ Phoebe】
Preface
If you don't understand bind Please go to Function.prototype.bind, I'm not going to repeat it here .
Want to see bind Principle kids' shoes , You need to know the following :
Ideas
bindMethod does not immediately execute the function , And you need to save an input parameter , So here we use Closure- Change the scope of the function , So use
applyperhapscallMethod to implement - Get all the input parameters of the function
arguments, And the use ofsliceConvert to an array
First use the above ideas to achieve a rough prototype of the implementation code :
Function.prototype.mybind = function () {
if (typeof this !== 'function') throw 'Bind must be called on a function'
let _this = this, // there this Is the original function
context = arguments[0],// Get to this Object to point to
slice = Array.prototype.slice,
args = slice.call(arguments, 1);// obtain bind Function division this Points to all parameters outside the object
// Return function
return function () {
args = args.concat(slice.call(arguments))// Merge bind Input parameter of the and input parameter of the execution
return _this.apply(context, args)
}
}
Now we can test :
function test(a, b) {
console.log('this.name', this.name)
console.log('a', a)
console.log('b', b)
return str
}
const henry = {
name: 'henry',
}
// test.bind(henry, 1)(2, 3)
test.mybind(henry, 1)(2, 3)
Okay , Now we have bind Basic usage , But it's not over , If we use bind The returned function is the constructor new What happens to an object ?
Prototype chain
Official documents There is a passage on :
A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.
This means that the binding function can also use new Operators create instances , Doing so is like constructing an objective function , Provided this Will be ignored , The prepositional parameters will also be used .
- We want the constructor of the instance to be the object function
- Detect the binding function
thisWhether it is an instance of the objective function , If yes, ignore the binding providedthis
...
context = this instanceof _this ? this : context
...
fn.prototype = _this.prototype
The complete code is :
Function.prototype.mybind = function () {
if (typeof this !== 'function') throw 'Bind must be called on a function'
let _this = this,
context = arguments[0],// Get to this Object to point to
slice = Array.prototype.slice,
args = slice.call(arguments, 1);// obtain bind Function division this Points to all parameters outside the object
// Return function
const fn = function () {
args = args.concat(slice.call(arguments))// Merge bind Input parameter of the and input parameter of the execution
context = this instanceof _this ? this : context // If this The constructor of the object pointed to is the original function , shows this yes new Objects generated in the process , At this point, ignore the context
return _this.apply(context, args)
}
fn.prototype = _this.prototype
return fn
}
Test it :
function test() {
}
const testBind = test.mybind()
const tb = new testBind()
console.log('tb', tb.constructor) //tb ƒ test() {}
It seems that I have no problem coming here , Let's take a look at the results of the following code execution
function test() {
}
const testBind = test.mybind()
const tb = new testBind()
testBind.prototype.say = function () {
console.log('say testBind')
}
test.prototype.say = function () {
console.log('say test')
}
tb.say() //say test
This is not true. bind Use new Result , The result should be say testBind That's right , This is because the prototype object of the binding function and constructor is the same , So we should use Object.create Optimize it , The complete code is as follows :
Function.prototype.mybind = function () {
if (typeof this !== 'function') throw 'Bind must be called on a function'
let _this = this,
context = arguments[0],// Get to this Object to point to
slice = Array.prototype.slice,
args = slice.call(arguments, 1);// obtain bind Function division this Points to all parameters outside the object
// Return function
const fn = function () {
args = args.concat(slice.call(arguments))// Merge bind Input parameter of the and input parameter of the execution
context = this instanceof _this ? this : context // If this The constructor of the object pointed to is the original function , shows this yes new Objects generated in the process , At this point, ignore the context
return _this.apply(context, args)
}
fn.prototype = Object.create(_this.prototype)
return fn
}
边栏推荐
- MFC dialog program core -isdialogmessage function -msg message structure -getmessage function -dispatchmessage function
- 【智能QbD风险评估工具】上海道宁为您带来LeanQbD介绍、试用、教程
- Matlab to find the limit
- Problem solving: modulenotfounderror: no module named 'pip‘
- How to create new user for ORACLE 19c (CDB & PDB)
- 解决问题:ModuleNotFoundError: No module named ‘pip‘
- NvtBack
- Can software related inventions be patented in India?
- Comment calculer Win / Tai / Loss in paired t - test
- 中职网络安全技能竞赛之应用服务漏洞扫描与利用(SSH私钥泄露)
猜你喜欢

倍福TwinCAT3 的OPC_UA通信测试案例

【云原生】2.4 Kubernetes 核心实战(中)

Simple introduction to matlab

How to create new user for ORACLE 19c (CDB & PDB)

Go Senior Engineer required course | I sincerely suggest you listen to it. Don't miss it~

Interview shock 61: tell me about MySQL transaction isolation level?

Qt中的UI文件介绍
![[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial](/img/00/9a6d17844b88f6921ad488f4975684.png)
[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial

Interview shock 61: tell me about MySQL transaction isolation level?

倍福控制器连接松下EtherCAT伺服注意事项
随机推荐
Proteus软件初学笔记
2022.6.28-----leetcode.324
深入理解 volatile 关键字
安装typescript环境并开启VSCode自动监视编译ts文件为js文件
C#通過中序遍曆對二叉樹進行線索化
超 Nice 的表格响应式布局小技巧
Qt的信号与槽
InDesign插件-常规功能开发-JS调试器打开和关闭-js脚本开发-ID插件
Beifu PLC controls servo through CANopen communication
Go Senior Engineer required course | I sincerely suggest you listen to it. Don't miss it~
三维模型下载与动画控制
qt json
Introduction to multi project development - business scenario Association basic introduction test payroll
Cereal mall project
MIT linear algebra Chinese Notes
PyGame accurately detects image collision
Factorization of large numbers ← C language
NvtBack
倍福控制器连接松下EtherCAT伺服注意事项
Principle and process of MySQL master-slave replication