当前位置:网站首页>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 ~
边栏推荐
- ASEMI大功率场效应管和三极管的区别
- Penetration test - directory traversal vulnerability
- Database query optimization method
- Mysql interactive_ Timeout and wait_ Timeout differences
- Google Earth engine (GEE) - Global jrc/gsw1_ 1 / batch download of yearlyhistory dataset (China region)
- Swift rapid development
- Kotlin compose listens to the soft keyboard and clicks enter to submit the event
- ThinkPHP 5 log management
- Mobile number regular expression input box loses focus verification
- Precise delay based on Cortex-M3 and M4 (systick delay of system timer can be used for STM32, aducm4050, etc.)
猜你喜欢

渗透测试-目录遍历漏洞

DOM document object model (I)

Rce code execution & command execution (V)

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

ASEMI三相整流桥的工作原理

How to install the blue lake plug-in to support Photoshop CC 2017

The SQL response is slow. What are your troubleshooting ideas?

What if the desktop computer is not connected to WiFi

Svg code snippet of loading animation

电脑的dwg文件怎么打开
随机推荐
Write shell script error summary
[keil] GPIO output macro definition of aducm4050 official library
Customize the console plot result style
Click to jump out and drag the pop-up window
SRC platform summary
How PHP gets the user's City
Go deep into the working principle of browser and JS engine (V8 engine as an example)
PHP calls map API
渗透测试-目录遍历漏洞
There is 404 in the laravel visit, except the home page is redirected; Index php
[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
Response (XI)
CTFHub-rce
Heavy broadcast | phase shift method + mathematical principle derivation of multi frequency heterodyne + implementation
《QDebug 2022年6月》
WPF uses Maui's self drawing logic
The print area becomes smaller after epplus copies the template
为什么SQL语句命中索引比不命中索引要快?
Chapter IX app project test (2) test tools
Laravel Aurora push