当前位置:网站首页>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 ~
边栏推荐
- Efficient NoSQL database service Amazon dynamodb experience sharing
- Huawei Hongmeng development lesson 4
- Precise delay based on Cortex-M3 and M4 (systick delay of system timer can be used for STM32, aducm4050, etc.)
- 魔法猪系统重装大师怎么使用
- dotnet-exec 0.4.0 released
- Separation of storage and computing in Dahua cloud native database
- 固态硬盘开盘数据恢复的方法
- Fun CMD command line~
- Vscade setting clang format
- XSS (cross site script attack) summary (II)
猜你喜欢

Attack and defense world web baby Web

CTFHub-rce

Ranorex Studio 10.1 Crack

Notes on non replacement elements in the line (padding, margin, and border)

【图像融合】基于matlab方向离散余弦变换和主成分分析图像融合【含Matlab源码 1907期】

MySQL prevents Chinese garbled code and solves the problem of Chinese garbled code

Activereportsjs V3.0 comes on stage

Compatible with Internet Explorer

In Net 6 using dotnet format formatting code

MySQL concept and operation (III)
随机推荐
SOC验证环境的启动方式
Ranorex Studio 10.1 Crack
[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
Why is the TCP handshake just 3 times?
Detailed summary of flex layout
Two hours to take you into the software testing industry (with a full set of software testing learning routes)
My IC journey - the growth of senior chip design verification engineers - "Hu" said that IC engineers are perfect and advanced
win11蓝牙无法连接怎么办?win11蓝牙无法连接的解决方法
Codeforces Round #802 (Div. 2) C D
SRC platform summary
Write shell script error summary
Creation and use of MySQL index
Flex flexible layout for mobile terminal page production
CSRF (Cross Site Request Forgery) &ssrf (server request forgery) (IV)
固态硬盘开盘数据恢复的方法
Specific operations for uploading pictures in PHP
Virtual honeypot Honeyd installation and deployment
great! Auto like, I use pyautogui!
2021-10-24
Integrate CDN to create the ultimate service experience for customers!