当前位置:网站首页>Bind simulation, key points of interpreting bind handwritten code [details]
Bind simulation, key points of interpreting bind handwritten code [details]
2022-06-25 05:04:00 【I am Feng Feng Yi】
bind What is it?
bind yes Function.prototype The method on the
Pass in an object , Returns a new function , Of the new function returned this Bound as an incoming object
In addition, parameter binding is supported , In other words, in addition to passing in an object , You can also pass in multiple parameters , As an argument to a function call .
This is a bind Basic use of , To put it bluntly, it is binding this, Returns a new function .
A chestnut
function func(a,b,c) {
console.log(this,a,b,c); // {name : "wxs"} 1 2 3
}
const funWithBind = func.bind({
name : "wxs"},1,2);
funWithBind(3);
ES6 basic bind The implementation of the
Function.prototype.bind = function (This,...args) {
if(typeof this !== 'function') {
throw new TypeError(`${
JSON.stringify(this)} is not a function`)
}
return function (...rest) {
// Image afferent number string This raw value ,call and apply Will help us package the object
return func.apply(This,args.concat(rest));
}
}
Is the code simple , This is the realization of bind The core function of
And a little bit more , Only function calls are supported here , I won't support it new.
adopt ES6 Syntax can be implemented very simply , Generally speaking, there are now babel You don't have to worry too much about compatibility
But what? , If the interview questions meet , You may want to pay attention to compatibility .
bind simulation
Use here ES5 To simulate bind The implementation of the , Take most of the cases into account .
Handwriting you see online bind Code for , It might look like this 
It feels so refined , But it is not easy to understand
It may be easier to understand this code after reading my code
I typed all the notes
// ES5 Grammar compatible new
// To understand this code , The idea of the Holy Grail model is needed
Function.prototype.bind = function () {
if(typeof this !== 'function') {
throw new TypeError(`${
JSON.stringify(this)} is not a function`)
} // this Non function
var func = this;
var This = arguments[0]; // Object to bind
var args = [].slice.call(arguments,1); // Parameter binding
var target = function () {
// The function to return
var rest = [].slice.call(arguments,0); // The remaining parameters
if(this instanceof target) {
// new Method call
// return new func(...args,...rest); // If ES6 Just do it , I will write one below ES6 Writing
This = this; // ES5 Use grail mode
}
return func.apply(This,args.concat(rest));
// This Don't worry about the original value ,call and apply I'll take care of it for you
}
function Temp() {
} // Used for Holy Grail mode
Temp.prototype = this.prototype;
target.prototype = new Temp();
return target;
}
A little bit online bind When the code handles the binding object, it does not transfer the binding object window To deal with
But I tried call and apply If you do not pass the bound object, you are bound window.
Maybe it's for compatibility processing
In addition, the code is not difficult to understand
The hard to understand estimate is why there are these lines of code
function Temp() {
} // Used for Holy Grail mode
Temp.prototype = this.prototype;
target.prototype = new Temp();
This is mainly to implement inheritance relationships , stay new The prototype chain can be accessed correctly .
If you don't understand, you can use the code I gave you
function func(a,b,c) {
console.log(this,a,b,c);
}
function A() {
this.lastName = 'w';
}
func.prototype = new A();
const funWithBind = func.bind(undefined,1,2);
// funWithBind(3);
const f = new funWithBind(3);
console.log(f.lastName);
Try to see what the problem would be without the Grail .
The Holy Grail mode doesn't understand ?
Never mind .
At the same time, I also published an article The holy grail mode The blog of , It's very detailed .
ES6 bind simulation
Function.prototype.bind = function (...args) {
if (typeof this !== 'function') {
throw new TypeError(`${
JSON.stringify(this)} is not a function`)
}
const func = this;
const [This, ...pervArgs] = args;
return function (...rest) {
if (new.target) {
return new func(...pervArgs, ...rest);
}
return func.apply(This, pervArgs.concat(rest));
}
}
If blogging helps you , Welcome to leave a message ~
边栏推荐
- 小白一键重装官网下载使用方法
- Laravel Vonage SMS sending
- Redis (17)
- [image fusion] image fusion based on MATLAB directional discrete cosine transform and principal component analysis [including Matlab source code 1907]
- Wechat applet new version prompt update
- Rce code execution & command execution (V)
- Mysql interactive_ Timeout and wait_ Timeout differences
- 两小时带你进入软件测试行业风口(附全套软件测试学习路线)
- Méthode de récupération des données d'ouverture du disque dur à l'état solide
- XSS (cross site script attack) summary (II)
猜你喜欢

Two hours to take you into the software testing industry (with a full set of software testing learning routes)

Working principle of asemi three-phase rectifier bridge

How to use the Magic pig system reinstallation master

Use js to simply implement the apply, call and bind methods

Sleep more, you can lose weight. According to the latest research from the University of Chicago, sleeping more than 1 hour a day is equivalent to eating less than one fried chicken leg

WPF uses Maui's self drawing logic
![[relax's law of life lying on the square] those poisonous chicken soup that seem to be too light and too heavy, but think carefully and fear](/img/12/d41f8d5abcb61d2632a8b117bf1604.jpg)
[relax's law of life lying on the square] those poisonous chicken soup that seem to be too light and too heavy, but think carefully and fear

TX Text Control 30.0 ActiveX

Activereportsjs V3.0 comes on stage

XSS (cross site script attack) summary (II)
随机推荐
SQL lab range explanation
Use js to simply implement the apply, call and bind methods
On Transform
Database overview
Laravel Vonage SMS sending
Wechat applet new version prompt update
Method of opening data recovery of solid state disk
【Keil】ADuCM4050官方库的GPIO输出宏定义
Apache+php uploading large files
Visual studio 2022 interface beautification tutorial
Region of Halcon: generation of multiple regions (3)
Using JS to realize the sidebar of life information network
Student achievement management system based on SSH
Leader: who can use redis expired monitoring to close orders and get out of here!
Qdebug June 2022
CTFHub-rce
XSS (cross site script attack) summary (II)
buuctf(pwn)
Separation of storage and computing in Dahua cloud native database
Write shell script error summary