当前位置:网站首页>The difference and usage of call, apply and bind
The difference and usage of call, apply and bind
2022-07-29 23:51:00 【oriental pajamas】
call, apply, bind
What call and apply have in common
- Common: Change the context of function execution, hand over the method of one object to another object for execution, and execute it immediately
- The object of call and apply must be a function
The difference between call and apply
Writing of call
Function.call(obj, [param1[, param2[, ...[, paramN]]]])
Note the following:
- The object to call call must be a function The first parameter of
- call is an object, and the caller of the Function will point to this object.If not passed, the default is the global object window
- Starting with the second parameter, it can receive any number of parameters, and each parameter will be mapped to the parameter of the Function in the corresponding position.
- But if all parameters are passed in as an array, they will be mapped to the first parameter corresponding to the Function as a whole, and then the parameters will be empty
function func(a,b,c) {}func.call(obj, 1,2,3) // The parameters received by func are 1,2,3func.call(obj, [1,2,3]) // The parameters received by func are [1,2,3], undefined, undefined
Writing of apply
Function.apply(obj[, argArray])
Note:
- Its caller must be a function, and only accepts two parameters, the first parameter is the same as call
- The second parameter must be an array or array-like, they will be converted into array-like, passed into the Function, and will be mapped to the corresponding parameters of the Function,
func.apply(obj, [1,2,3]) // The parameters received by func are 1,2,3func.apply(obj, {0:1, 1:2, 2:3, length: 3}) // the parameters received by func are 1,2,3
What is an array-like
- Objects with array-like characteristics
- Class arrays cannot use methods on the array prototype chain such as forEach, splice, push, etc.
Use of call and apply
Call usage scenarios
- Object inheritance
function superClass() {this.a = 1this.print = function() {console.log(this.a)}}function subClass() {superClass.call(this)this.print()}subClass() // 1
- Borrowed method* class array, if you want to use the method on the Array prototype chain*
let demoNodes = Array.prototype.slice.call(document.getElementsByTagName("*"))
Use of apply
- Math.max, used to get the largest item in the array*
let max = Math.max.apply(null, array)
- Merge two arrays
let arr1 = [1, 2, 3]let arr2 = [4, 5, 6]Array.prototype.push.apply(arr1, arr2)console.log(arr1) // [1, 2, 3, 4, 5, 6]
Use of bind
The bind() method creates a new function, sets the this keyword to the provided value when calling the new function, and uses the given parameter list as the first few items of the original function's parameter sequence when calling the new function
Function.bind(thisArg, arg1, arg2])
- The
- bind method is similar to apply and call, and it can also change the this pointer in the function body. The difference is that the return value of the bind method is a function, which needs to be called later to execute.And apply and call are called immediately
- If the first parameter of bind is null or undefined, this points to the global object window
function add (a, b) {return a + b;}function sub (a, b) {return a - b;}add.bind(sub, 5, 3); // this time, it will not return 8add.bind(sub, 5, 3)(); // after calling, return 8
Summary
- The main function of
- call and apply is to change the execution context of the object and execute it immediately.They are written slightly differently on the parameters.* bind can also change the execution context of the object. Unlike call and apply, the return value is a function, and it needs to be called later to execute.Mock implementation of bind
=========
bind
Thebind() method creates a new function. When the new function is called, the first parameter of bind() will be used as this when it runs, and the following series of parameters will be passed in the passed arguments.input as its parameter
function fn(a, b, c) {return a + b + c;}var _fn = fn.bind(null, 10);var ans = _fn(20, 30); // 60
Its features:
1. Returns a function;
2. Parameters can be passed in
Implement bind final code
Function.prototype.bind1 = function(context) {if (typeof this !== 'function') {throw new Error('Function.prototype.bind --what is trying to be bound is not callable')}var self = thisvar args = Array.prototype.slice.call(arguments, 1)var fNOP = function () {}var fBound = function() {var bindArgs = Array.prototype.slice.call(arguments) // When used as a constructor, this points to the instance, and the result is true at this time. Point the this of the binding function to the instance, so that the instance can get the value from the binding function// Take the demo above as an example, if you change it to`this instanceof fBound ? null : context`, the instance is just an empty object, change null to this, the instance will have the habit attribute // When used as a normal function, this points to window, and the result is false at this time, and the bound function'sthis points to context return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs))}fNOP.prototype = this.prototypefBound.prototype = new fNOP()return fBound}
边栏推荐
- devops学习(九) Helm工具--持续部署
- windows下 PHP 安装
- Raspberry pie wiringPi 2.6 installed on solving gpio readall command mistakes
- Access Modbus TCP and Modbus RTU protocol devices using Neuron
- MySQL【基本select语句】
- In 2022, the latest Gansu construction staff (material staff) mock exam questions and answers
- Install PyCharm on Raspberry Pi
- 暴力递归到动态规划 04 (数字字符串转化)
- Super RVRT
- devops学习(六)Jenkins 持续部署-版本选择
猜你喜欢
jenkins use and maintenance
logback过期日志文件自动删除
一文看懂拉格朗日乘子法、KKT条件和对偶问题
Dropout回顾
Gao Shu Xia|Triple Integral Exercises|Uncle Gao Shu|Handwritten Notes
Raspberry pie wiringPi 2.6 installed on solving gpio readall command mistakes
DNA修饰碱基5-甲基胞嘧啶和8-羟基鸟嘌呤|DNA修饰量子点|规格信息
接口测试的概念、目的、流程、测试方法有哪些?
接口性能测试方案设计方法有哪些?要怎么去写?
Foxmail是什么邮箱?
随机推荐
SQL Server、MySQL主从搭建,EF Core读写分离代码实现
29岁从事功能测试被辞,面试2个月都找不到工作吗?
leetcode122. Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II(简单)
全国双非院校考研信息汇总整理 Part.3
容器化 | 在 Rancher 中部署 MySQL 集群
C陷阱与缺陷 第5章 库函数 5.4 使用errno检测错误
【leetcode】The sword refers to Offer II 002. Binary addition
call、apply 以及 bind 的区别和用法
桌面软件开发框架大赏
esp12f + tft 显示图片问题
[leetcode] 82. Delete duplicate elements in sorted linked list II (medium)
C陷阱与缺陷 第5章 库函数 5.3 缓冲输出与内存分配
esp12f + tft display picture problem
C陷阱与缺陷 第4章 链接 4.4 形参、实参与返回值
暴力递归到动态规划 03 (背包问题)
Android 11 : 隐私和安全
仿牛客论坛项目部署总结
How to make labview an application (labview program recognizes shapes)
Prometheus 的功能特性
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》