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 define the use of call and apply of JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to define the use of call and apply of JavaScript". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to define the use of call and apply of JavaScript" can help you solve the problem.

Define

Call and apply: when the function transfer call () method is executed, the this in the function points to the first parameter value, except for several branches after the first parameter value, which are passed into the function, in short, to change the this direction of the function at run time.

Use examples: fn.call (obj, args1, args2...), fn.apply (obj, [arg1, arg2...]), call and apply calls are the same except for the second parameter transfer method.

For example, 1:

Var obj = {name: 'programmer rice noodles'}; function fn () {console.log (this.name)} fn () / / this.name = > undefinedfn.call (obj) / / this.name = > 'programmer rice noodles'

Summary:

1. When the fn function transfers the call method to execute, the this of the function points to obj.

2. Both the call method and the fn function are executed.

If you still don't understand, when fn.call (obj) executes, it can be seen as having a fn function executed in the obj object. Then the this point in the fn function is obj.

Another example is 2:

Var obj = {name: 'programmer rice noodles', fn: function () {console.log (this.name)}}; obj.fn (); / / this.name = > 'programmer rice noodles'

Summary:

1. When fn.call (obj) in example 1 is executed, it is equivalent to example 2 obj.fn (); when the call method is called, it will change the execution context of the current calling function (that is, change the this direction).

Simulation step 1

Example 1:

Var obj = {name: 'programmer rice noodles'}; function fn () {console.log (this.name)} fn.call (obj) / / this.name = > 'programmer rice noodles'

Example 2:

Var obj = {name: 'programmer rice noodles', fn: function () {console.log (this.name)}}; obj.fn (); / / this.name = > 'programmer rice noodles'

To implement your own myCall method, first look at the difference between the test obj object in example 1 and example 2.

Different:

1. Example 2 adds the fn function method to obj.

2. Example 2 execution method is obj.fn () execution, while example 1 execution method is fn.call (obj).

This is easy. How can we transform example 1 into example 2?

Let's summarize the steps:

1. Set the fn function as a property of the object.

2. Call the fn function to execute.

3. After the call, delete the fn property (function) from the object. (an attribute has been added to the object, which can be deleted after we call it.)

With the idea, we can write the code like this:

````jsobj.fn = fn;obj.fn (); delete obj.fn; / / Delete attribute ```

According to the above idea, then according to this idea, write our own myCall method:

````jsFunction.prototype.myCall = function (context) {context.fn = this; context.fn (); delete context.fn;}; var obj = {name: 'programmer rice noodles'}; function fn () {console.log (this.name);} fn.myCall (obj) / / this.name = > 'programmer rice noodles' ````

Execute the myCall method, and you can see that this points to the obj object and prints the expected value, so the first step of this method is complete!

Simulation step 2

Continue to refine the myCall method, change the fn method, add two parameters, and then execute the method.

Function fn (index, value) {console.log (this.name); console.log (index, value);} fn.myCall (obj, 111l,'I am a value'); / / this.name = > 'programmer rice noodles' / / undefined, undefined

Execute a fn function, only print a value, pass in the parameters, do not print out. The method needs to be modified so that the parameters can also be printed. We can take a value from the arguments object, and the arguments object represents the object passed in by the function. Just print it.

Function.prototype.myCall = function (context) {console.log (arguments); context.fn = this; context.fn (); delete context.fn;}

The printed arguments object:

We can see that the structure of the arguments object is:

{'0customers: {name:' programmer rice noodles'}, '1values: 111,' 2values:'I am a value'}

0 represents the first parameter passed in, 1 represents the second parameter, and so on. We see that arguments is a class array, so we can use array methods to store it, and since we're just getting parameters, we start with 1.

Var args = []; for (var I = 1; I

< arguments.length; i++) { args.push('arguments[' + i + ']');}// args为 ["arguments[1]", "arguments[2]", "arguments[3]"] 取值的参数的问题解决了,我们下一步解决一下,如何把这些参数传给函数执行。 // 思考一下,怎样才能这样传参给fn函数执行context.fn(arguments[1], arguments[2]); 可能有人想到如下方法: // 把数组里的元素通过join方法,传进函数的形参里context.fn(args.join(','))// 这样的话,其实 context.fn(args.join(','))执行变成:context.fn("arguments[1]", "arguments[2]");// 变成了一个字符串,变成了一个死值了,无论传什么,都变成字符串 "arguments[1]", "arguments[2]" 。。。。 可以有人又想到用ES6方法来解决。这个call是ES3的方法,所以还是不用ES6方法解决。 其实我们可以用 eval方法来解决。查文档得知 eval() 函数会将传入的字符串当做 JavaScript 代码进行执行。这到底是什么意思? eval() 的参数是一个字符串。如果字符串表示的是表达式,eval() 会对表达式进行求值。如果参数表示一个或多个 JavaScript 语句,那么eval() 就会执行这些语句。 举个例子: console.log(eval('2 + 2')); // 2 + 2 =>

4. The final output is 2console.log (eval ('context.fn (' + args +')) / / equivalent to running context.fn (arguments [1], arguments [2],...), using eval to execute a string of JavaScript statements.

More detailed links to eval

Args automatically calls the Array.toString () method. Automatic execution through eval becomes context.fn (arguments [1], arguments [2]).

The code is as follows:

Var obj = {name: 'programmer rice noodles'}; function fn (index, value) {console.log (this.name); / / programmer rice noodles console.log (index, value); / / 111I am a value} Function.prototype.myCall = function (context) {context.fn = this; var args = []; for (var I = 1; I

< arguments.length; i++) { args.push('arguments[' + i + ']'); } eval('context.fn(' + args + ')'); delete context.fn;};fn.myCall(obj, 111, '我是一个值'); // this.name =>

'programmer rice noodles'

Execute the method, the input is completely in line with our expectations, and we finally got it!

The first parameter in step 3 of the simulation is null or undefined,this pointing to window.

For example:

Var name = 'programmer rice noodles' function fn () {console.log (this.name); / / programmer rice noodles} fn.call (null); / / this.name = > 'programmer rice noodles'

When fn executes, it still outputs this.name = 'programmer rice noodles'. What does that mean? as long as the first parameter passes null or undefined, the function calls the call method, and this points to window.

Function executes the call method, and if there is a return value, it returns.

For example:

Var name = 'programmer rice noodles' function fn () {console.log (this.name); / / programmer rice noodles return {name: this.name}} fn.call (null) / / this.name = > 'programmer rice noodle' / / execute the fn function to return the object directly / / {/ / name: 'programmer rice noodle' / /} the final version implements the call code var obj = {name: 'programmer rice noodle'}; function fn (index, value) {console.log (this.name); / / programmer rice noodle console.log (index, value) / / 111I am a value return {name: this.name, index: index, value: value};} Function.prototype.myCall = function (context) {var context = context | | window; context.fn = this; var args = []; for (var I = 1; I

< arguments.length; i++) { args.push('arguments[' + i + ']'); } var result = eval('context.fn(' + args + ')'); delete context.fn; return result;};fn.myCall(obj, 111, '我是一个值'); // this.name =>

Programmer Rice Noodle / / final output / / {/ / name: "programmer Rice Noodle" / / index: 111 value / value: "I am a value" / /} implement apply code

Since the implementation principle of apply is basically the same as that of call, I will not elaborate on it and go straight to the code:

Function.prototype.myApply = function (context, arr) {var context = context | | window; context.fn = this; var result; if (! arr) {result = context.fn ();} else {var args = []; for (var I = 0; I < arr.length) Args.push +) {args.push ('arr [' + I +']');} result = eval ('context.fn (' + args +')');} delete context.fn; return result;}; this is the end of the introduction on "how to define the use of call and apply in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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