[Blog recommendations] usage of bind, call, and apply functions in Javascript

Source: Internet
Author: User

[Blog recommendations] usage of bind, call, and apply functions in Javascript

When introducing js to other programs in our project team, I have prepared a lot of content, but it seems that the effect is not very good. I can't just say it, but I must do it. Someone asked me a few days ago about the usage of the call () function in the code. I asked him to read the book. Here I recommend using js to write the server program.The essence of javascript programmingThis book is not covered by crockford. After thatSegmentfaultI saw a similar question again, and I wrote a note here after I answered the question.

For details about how to define classes or objects in js, seeW3school hereHere, I will not go into details.

To introduce the usage of the bind, call, and apply functions, we have to introduce some settings of functions in js. Read-through is recommended for this part.The essence of javascript programmingIn chapter 4, what I mentioned here can be found in books.

For more information about the three functions, see the MDN documentation:Bind,Call,Apply.

Next, let's start to change the answer on segmentfault:

Function calling in js has four modes:Method call, normal function call, constructor function call, and apply/call.

In addition to the parameter defined during the declaration, no matter which function call, two parameters, this and arguments, are automatically added.

Arguments does not involve the above three functions, so here we only talk about this. The value of this. In the above 4 call mode, different values are bound respectively. Let's talk about it separately:

Method call:

This is easy to understand. A function is an object attribute, such

 
 
  1. var a = {     
  2.     v : 0,     
  3.     f : function(xx) {                 
  4.         this.v = xx;     
  5.     } 
  6. a.f(5); 

At this time, this in the above function is bound to this object. Therefore, this. v can obtain the attribute v of object.

Normal function call:Still read code

 
 
  1. function f(xx) {         
  2.     this.x = xx; 
  3. f(5); 

At this time, this in function f is bound to a global object. If it is in the interpreter running in the browser, it is generally a window object. So here this. x actually accesses window. x. Of course, if the window does not have the x attribute, you should add an x attribute to the window object and assign a value to it according to the pitfalls Syntax of js.

Constructor function call:

Constructor has always been the most boring part of js, because it is incompatible with the prototype-Based Object-Oriented implementation method originally designed by js, it is like a habit to cater to the fact that everyone has been spoiled by other class-based facial objects.

If you call a function with the new Keyword, js will create a prototype attribute, which is a new object of the function. When you call this function, bind this to the new object. Of course, the new Keyword also changes the behavior of the return statement, but we will not talk about it here. View code

 
 
  1. function a(xx)
  2. {         
  3.     this.m = xx; 
  4. var b = new a(5); 

There is no difference between the above function and the method of writing normally called functions, but the keyword new is added before the function name during the call. In this way, this is no longer bound to the global object mentioned above, but to the new object created here, so this method is actually very dangerous, because simply looking at the function, you don't know whether this function is intended to be used as a constructor or a common function. So we can see that in jslint, it requires all the constructors you write, that is, once it finds that you use the new Keyword, the first letter of the subsequent function must be capitalized, in this way, the first letter of the function is capitalized. I personally have only one opinion: JACK :)

Apply/call:

As we know, in js, a function is actually an object, so a function can naturally have its own method, which is a bit of a wrap. In js, each Function has a common prototype -- Function, and this prototype has several attributes and Methods. Here, the bind, call, and apply methods are confusing. Let's talk about the apply method first. It allows us to construct a parameter array and pass it to the function. At the same time, we can set the value of this on our own. this is the most powerful part of this method. The above three function call methods are described as follows, as you can see, this is automatically bound and cannot be set by you. When you want to set it, you can use apply. The apply function receives two parameters. The first is the value passed to this function to bind this, and the second is a parameter array.

View code

 
 
  1. function a(xx) {         
  2.     this.b = xx; 
  3. var o = {}; 
  4. a.apply(o, [5]); 
  5. alert(a.b);    // undefined 
  6. alert(o.b);    // 5 

Isn't it amazing that function a can add an attribute value to function o. Of course, if you pass null in the first parameter of apply, the this pointer will still be bound to the Global Object in function.

The call () and apply () methods are similar. They exist to change the binding of this. What is the difference between call () and apply? In my opinion, there is no difference between birds... Joke! As mentioned above, apply () receives two parameters. The first is to bind the value of this, and the second is a parameter array. Note that it is an array, all parameters you want to pass to this function are placed in the array, and then the apply () function will automatically help you expand the array when calling the function. In call (), its first parameter is also bound to the value of this, but what is accepted later is an indefinite parameter, instead of an array, that is to say, you can pass these parameters one by one just like passing parameters to functions.

So if there is any difference, it looks like this.

 
 
  1. function a(xx, yy) {     
  2.     alert(xx, yy);     
  3.     alert(this);     
  4.     alert(arguments); 
  5. a.apply(null, [5, 55]); 
  6. a.call(null, 5, 55); 

That's all.

Finally, for the bind () function, whether it is call () or apply (), it immediately calls the corresponding function, and bind () does not, bind () generates a new function. The parameters of the bind () function are the same as those of the call () function. The first parameter is the value bound to this function, and the variable parameters passed to the function are accepted later. After the new function generated by bind () is returned, you can call the function whenever you want, and you can see the code.

 
 
  1. var m = {    
  2.     "x" : 1 
  3. }; 
  4. function foo(y) { 
  5.     alert(this.x + y); 
  6. foo.apply(m, [5]); 
  7. foo.call(m, 5); 
  8. var foo1 = foo.bind(m, 5); 
  9. foo1(); 

In the end, you want to define a function in js, so you will write:

 
 
  1. 1function jam() {}; 

In fact, this is a syntactic sugar in js, which is equivalent:

 
 
  1. var jam = function() {}; 

Then, if you want to execute this function, you will write it as follows:

 
 
  1. function jam() {}(); 

However, if this is the case, an error is reported. In fact, this writing method is not an error because it is indeed a function expression supported by js, but js also specifies that the statement starting with function is considered a function statement, however, the function statement will certainly not be followed by (), so an error is reported. Therefore, a clever person can come up with a pair of parentheses. So it becomes like this:

1 (function jam (){}());

This defines a function and executes it at the same time. For more information, seeECMAScriptOfExpression StatementChapter.

This article from the "cainiao surfaced" blog, the original link: http://rangercyh.blog.51cto.com/1444712/1615809

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.