A detailed description of bind, call, and apply functions in JavaScript

Source: Internet
Author: User

In the other program for our project to introduce JS, I prepared a lot of content, but it does not seem to be very effective, really light or not, it must be hands-on. A few days ago someone asked me about the use of the call () function in the code, I let him go to read a book, here is recommended to use JS to write the server program ape See "JavaScript Programming Essence" this, Crockford big God is not covered. Then I saw a similar problem on the Segmentfault , and after that the answer is here to write a pen.

First of all, about JS definition class or Object method, please see here w3school Here, write very detailed and clear, I no longer explain.

In order to introduce the use of the three functions of bind, call, and apply, we have to introduce some settings of the JS function. This part of the recommendation reads through the fourth chapter of the essence of JavaScript programming , which I can find in the book.

For a detailed description of these three functions, you can refer to the documentation for MDN:bind, call,apply.

Below begin to move bricks, modify the answer before the ego on Segmentfault:

There are 4 modes of function calls in JS: method Invocation, normal function call, constructor function call, Apply/call call.

At the same time, no matter what function call except for the formal parameters that you define when you declare, you will automatically add 2 parameters, respectively, this and arguments.

Arguments does not involve the above 3 functions, so this is the only one here. The value of this, in the above 4 invocation mode, will bind different values, respectively. Say, separately:

Method invocation:

It's good to understand that a function is a property of an object, such as

var a = {         v:0,         f:function (xx) {                         this.v = xx;         }} A.F (5);

At this point, the this in the above function binds to this object A. So THIS.V can take the property of object a V.

normal function call: still look at the code

function f (xx) {             this.x = xx;} f (5);

At this point, the this in the function f is bound to the global object, in the case of a browser-run interpreter, typically a window object. So here this.x access is actually window.x, of course, if the window does not have the X attribute, then you write, according to JS's pit father syntax, is to add an X attribute to the Window object, and assign a value.

constructor function Call:

The constructor has always been I think is JS in the most pit-father part, because it and JS originally designed based on the prototype-oriented implementation of the way out of tune, as if deliberately to cater to everyone has been other class-based face objects implemented to spoil the habit.

If you call with the New keyword in front of a function, JS creates a prototype property that is a new object for this function, and binds this to the new object when the function is called. Of course the New keyword will also change the behavior of the return statement, but it will not be discussed here. Look at the code

function A (xx) {             this.m = xx;} var b = new A (5);

There is no difference between this function and the normal call function, except that the function name is preceded by the keyword new, so that the this binding is no longer the global object mentioned above, but the new object is created here, so it is very dangerous to say this way, because light looks at the function, You don't know whether this function is intended to be used as a constructor or as a general function. So we can see that in JSLint, it will require you to write all the constructors, that is, once it finds that you have used the new keyword, then the first letter of the function must be capitalized, so that the letter is capitalized in the way to distinguish, I personally only one view: Pit Dad:)

Apply/call Call:

We know that in JS, the function is actually an object, then the function can also have its own method, a bit around, in JS, each function has a common prototype--function, and this prototype comes with several properties and methods, which there are confusing bind, Call, apply method. First say the Apply method, it let us construct a parameter array passed to the function, but also can set the value of this, which is its most powerful place, the above 3 function call way, you can see, this is automatically bound, no way to set up, when you want to set, you can use apply (). The Apply function receives 2 parameters, the first one is passed to the value that this function binds to, and the second is an array of arguments.

Look at the code

function A (xx) {             this.b = xx;} var o = {}; a.apply (O, [5]); alert (A.B)    ; Undefined alert (O.B);    5

is not very magical, function a actually can give o plus attribute value. Of course, if you pass NULL for the first argument of apply, the this pointer will still bind the global object in function A.

The call () method is very similar to the Apply () method, and they all exist in order to change the binding of this, what is the difference between call () and apply ()? As far as I'm concerned, there is no bird difference ... Just kidding! Apply () to receive two parameters, the first is the value of the binding this, the second is an array of parameters, note that it is a set of parameters that you want to pass to the function in the array, and then the Apply () function will automatically help you to expand the array when calling the function. and call (), its first parameter is also bound to the value of this, but the subsequent acceptance is an indeterminate parameter, and is no longer an array, that is, you can give the function as usual to the parameters of one pass.

So if there's any difference, it looks like this.

function A (xx, yy) {         alert (xx, yy);         alert (this);         alert (arguments); } a.apply (null, [5, 55]); A.call (NULL, 5, 55);

That's all.

Finally, the bind () function, either call () or apply () is called immediately the corresponding function, and bind () does not, bind () will generate a new function, the bind () function parameter is consistent with call (), the first parameter is also tied The value of this, followed by an indeterminate argument passed to the function. The new function generated by bind () returns, when you want to tune it, and look at the code to see

var m = {        "x": 1}, function foo (y) {     alert (this.x + y),} foo.apply (M, [5]); Foo.call (M, 5); var foo1 = Foo.bind (M, 5); Foo1 ();

Finally, a spit slot, you want to define a function in JS, so you will write:

function Jam () {};

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

var jam = function () {};

And then you want to execute this function, the brain hole opens up so you'll write:

function Jam () {} ();

But this write error, in fact, this method is not wrong, because it is really a function of JS support expression, but at the same time JS also stipulates that the statement at the beginning of function is considered to be a functional statement, and the function statement is definitely not take (), so the error, so smart people want to come out, Add a pair of parentheses to it. And that's how it turns out:

1 (function Jam () {} ());

This defines a function that also executes it, with details participating in the ECMAScript Expression Statement chapter.

The above excerpt from the code farm: http://www.codeceo.com/article/javascript-bind-call-apply.html

The original from the novice surfaced The water blog: http://rangercyh.blog.51cto.com/1444712/1615809

A detailed description of bind, call, and apply functions in JavaScript

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.