Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JS to simply implement apply, call and bind methods

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use JS to simply implement apply, call and bind methods". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to use JS to simply implement apply, call and bind methods".

1. Method introduction

Apply, call and bind are all built-in methods provided to us by the system, and every function can use these three methods because apply, call and bind are all implemented on the prototype of Function (Function.prototype), and their role is to explicitly bind this to our function calls. Let's first introduce their basic usage:

The apply method: calls a function with a given th value and parameters provided in the form of an array (or class array object).

Use syntax: func.apply (thisArg, [argsArray])

ThisArg: the argsArray value bound when the func function is called; [argsArray]: an array or class array object in which the array elements are passed to the func function as separate arguments

Use effect:

Function foo (x, y, z) {console.log (this, x, y, z)} const obj = {name: 'curry', age: 30} / * * 1. Bind the obj object to this * 2 of the foo function. The 1 / 2 / 3 of the array is passed to the three parameters * / foo.apply (obj, [1, 2, 3]) corresponding to the foo function.

Call method: calls a function with a specified this value and one or more parameters given separately.

Use syntax: func.call (thisArg, arg1, arg2,...)

ThisArg: the arg1 value bound when the func function is called; arg1, arg2,...: the specified parameter list, which will be passed to the func function as an argument

Use effect:

Function foo (x, y, z) {console.log (this, x, y, z)} const obj = {name: 'curry', age: 30} / * * 1. Pass the a b c in the remaining parameters of the this * 2.call bound the obj object to the foo function to the corresponding three parameters * / foo.call of the foo function (obj, 'foo.call,' bounded,'c')

The bind method: creates a new function whose this is specified as the first argument to bind () when bind () is called, and the remaining parameters are used as arguments to the new function.

Use syntax: func.bind (thisArg [, arg1 [, arg2 [,...])

ThisArg: the value passed to the target function as a this parameter when the func function is called; arg1, arg2,...: the parameter that is preset into the parameter list of the func function when the target function is called

Use effect:

Function foo (... args) {console.log (this,... args)} const obj = {name: 'curry', age: 30} / * 1. Pass 1 / 2 / 3 of the remaining parameters of the this * 2.bind bound the obj object to the foo function to the parameter * 3 in the foo function, respectively. You can also pass parameters when newFoo is called, and then the parameters passed by bind will be merged with the parameters passed when newFoo is called * / const newFoo = foo.bind (obj, 1, 2, 3) newFoo () newFoo ('averse,' baked,'c')

Summary:

Apply and call are mainly used to bind the corresponding values to the this of the function when the function is called, except for the first parameter, the apply method accepts an array of parameters, while the call method accepts a list of parameters.

Bind also specifies the value bound by this to the function. Unlike apply and call, it returns a new function. The this point in the new function is the value we specified, and the parameters passed in will be merged.

Implementation of 2.apply, call and bind methods

In order for all defined functions to use our custom apply, call and bind methods, we need to hang our own implementation methods on the Function prototype, so that all functions can find custom three methods through the prototype chain.

The implementation of 2.1.apply Function.prototype.myApply = function (thisArg, argArray) {/ / 1. Get the function that needs to be executed / / because myApply needs to be called by the current function. According to the implicit binding of this, the this here points to the function const fn = this / / 2 that needs to be executed. Judge the boundary of the incoming thisArg if (thisArg = null | | thisArg = undefined) {/ / when the null or undefined is passed, the this of the executed function points directly to the global window thisArg = window} else {/ / to objectify the incoming thisArg, which is convenient to add the attribute thisArg = Object (thisArg)} / / to thisArg later. It can also be written as a ternary operator: / / thisArg = (thisArg = = null | | thisArg = = undefined)? Window: Object (thisArg) / / 3. Add the acquired fn to the thisArg object / / the reason for using Symbol here is to avoid conflicts between the attributes in the incoming thisArg and adding fn const fnSymbol = Symbol () Object.defineProperty (thisArg, fnSymbol, {enumerable: false, configurable: true, writable: false, value: fn}) / / can also be written simply as / / thisArg [fnSymbol] = fn / / 4. Judge argArray / / to see if there is an input value. If no value is passed, the default is [] argArray = argArray | | [] / / 5. Call the acquired fn function and pass the corresponding array expansion to const result = thisArg [fnSymbol] (... argArray) / / delete the added attribute delete thisArg [fnSymbol] / / 6 after the call. Return the result to return result}

Test: although the Symbol attribute still exists in the printed object, it has actually been deleted through delete, here is the problem of object reference.

Function foo (x, y, z) {console.log (this, x, y, z)} foo.myApply ({name: 'curry'}, [1, 2, 3])

The realization of 2.2.call

The implementation of the call method is similar to that of the apply method, mainly in the processing of the following parameters.

Function.prototype.myCall = function (thisArg,... args) {/ / 1. Get the function const fn = this / / 2 that needs to be executed. Judge the boundary of the incoming thisArg thisArg = (thisArg = = null | | thisArg = undefined)? Window: Object (thisArg) / / 3. Add the acquired fn to the thisArg object const fnSymbol = Symbol () thisArg [fnSymbol] = fn / / 4. Call the acquired fn function and pass the corresponding args to const result = thisArg [fnSymbol] (... args) / / delete the added attribute delete thisArg [fnSymbol] / / 5 after the call. Return the result to return result}

Test:

Function foo (x, y, z) {console.log (this, x, y, z)} foo.myCall ({name: 'curry'}, 1, 2, 3)

The realization of 2.3.bind

The implementation of the bind method is a little more complex and needs to take into account the issue of parameter merging.

Function.prototype.myBind = function (thisArg,... argsArray) {/ / 1. Get the current objective function, that is, the function const fn = this / / 2 that currently uses the myBind method. Judge the boundary of the incoming thisArg thisArg = (thisArg = = null | | thisArg = undefined)? Window: Object (thisArg) / / 3. Add the acquired fn to the thisArg object const fnSymbol = Symbol () thisArg [fnSymbol] = fn / / 4. Define a new function function newFn (... args) {/ / 4. 1. Merge the parameter const allArgs passed in by myBind and newFn: const allArgs = [... argsArray,... args] / / 4.2. Call the function that really needs to be called, and pass the merged parameters to const result = thisArg [fnSymbol] (. AllArgs) / / 4.3. Delete the added attribute delete thisArg [fnSymbol] / / 4. 4. Return the result to return result} / / 6. Return the new function to return newFn}

Test:

Function foo (x, y, z) {console.log (this, x, y, z)} const newFoo = foo.myBind ({name: 'curry'}, 1, 2) newFoo (3)

Thank you for your reading, the above is the content of "how to use JS to simply implement apply, call and bind methods". After the study of this article, I believe you have a deeper understanding of how to use JS to simply implement apply, call and bind methods, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report