当前位置:网站首页>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, undefinedWriting 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,3What 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 8Summary
- 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); // 60Its 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}边栏推荐
猜你喜欢
随机推荐
C陷阱与缺陷 第5章 库函数 5.2更新顺序文件
WLAN笔记
50. Leetcode 】 【 Pow (x, n) (medium) (power) quickly
jenkins use and maintenance
资源集合
C语言初阶-初识C语言
JetsonNano learning (6) Big pits and solutions that Jetson stepped on___Continuously updated
Foxmail是什么邮箱?
Framework 到底该怎么学习?
[2023 School Recruitment Questions] Summary of knowledge points and hand-tear code in the written test and interview
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
管理区解耦架构见过吗?能帮客户解决大难题的
PyTorch笔记 - Attention Is All You Need (1)
Elementary C language - first understanding of C language
关于MySQL索引的一些个人理解(部分参考MySQL45讲)
C陷阱与缺陷 第5章 库函数 5.4 使用errno检测错误
29岁从事功能测试被辞,面试2个月都找不到工作吗?
devops学习(九) Helm工具--持续部署
ApplicationContext的三大实现
全国双非院校考研信息汇总整理 Part.4









