Call, apply, bind, and applybind in javascript

Source: Internet
Author: User
Tags define function

Call, apply, bind, and applybind in javascript

In JavaScript, call, apply, and bind are the three methods that come with the Function object. The main Function of these three methods is to change this point in the Function, in this way, you can achieve the effect of 'moving flowers and times. This article will explain the three methods in detail and list several classic application scenarios.

Call(ThisArgs [, args...])

This method can pass a thisArgs parameter and a parameter list. thisArgs specifies the caller of the function at runtime, that is, the this object in the function, and the parameter list is passed into the call function. ThisArgs has the following values:

(1) do not pass, or pass null, undefined. this in the function points to the window object.

(2) Pass the function name of another function. this in the function points to the reference of this function.

(3) pass basic types such as String, value, or Boolean type. this in the function points to the corresponding packaging object, such as String, Number, and Boolean.

(4) pass an object. this in the function points to this object.

Function a () {console. log (this); // this object in output function a} function B () {}// define function bvar obj = {name: 'onepixel '}; // define the object obja. call (); // wa. call (null); // calls wa. call (undefined); // calls wa. call (1); // Numbera. call (''); // Stringa. call (true); // Booleana. call (B); // function B () {}. call (obj); // Object

This is the core function of call. It allows you to call a method that is not defined by this object, and this method can access the attributes of this object. What are the advantages of this method, I will talk about it later. Let's take a look at a simple example:

Var a = {name: 'onepixel ', // defines the attribute say: function () {// defines the method console of. log ("Hi, I'm function! ") ;}}; Function B (name) {console. log ("Post params:" + name); console. log ("I'm" + this. name); this. say ();} B. call (a, 'test');> Post params: testI'm onepixelI'm function!

When B. during call, the string 'test' is passed to function B as a parameter. Because of the call function, this in function B points to object a, which is equivalent to calling function B on Object, in fact, a does not define B.

Apply(ThisArgs [, args [])

The only difference between apply and call is that the transfer method of the second parameter is different. The second parameter of apply must be an array, and call allows passing a list of parameters. It is worth noting that, although apply receives a parameter array, it is passed in the form of a parameter list when it is passed to the called function. Let's look at a simple example:

function b(x,y,z){  console.log(x,y,z);}b.apply(null,[1,2,3]); // 1 2 3

This feature of apply is very important. We will mention this feature in the following application scenarios.

Bind(ThisArgs [, args...])

Bind is a new method added to ES5. Its parameter passing is similar to call, but it is significantly different from call/apply, that is, call or apply will automatically execute the corresponding function, the bind does not execute the corresponding function, but returns a reference to the function. At first glance, the bind seems to lag behind call/apply. Why should ES5 introduce bind?

In fact, the real purpose of ES5's bind introduction is to make up for the call/apply deficiency. Because call/apply will automatically execute the target function, it cannot be used in the event binding function, because the event binding function does not need to be manually executed, it is automatically executed by JS when the event is triggered. While the bind implements changing the function this, it does not automatically execute the target function. Therefore, the above problem can be solved perfectly. You can see the following example:

Var obj = {name: 'onepixel '};/*** Add a click event listener to the document and bind the onClick function * to set this of onClick to obj through the bind method, and pass the parameter p1, p2 */document. addEventListener ('click', onClick. bind (obj, 'p1', 'p2'), false); // triggered when a webpage is clicked and executed function onClick (a, B) {console. log (this. name, // onepixel a, // p1 B // p2 )}

When a Web page is clicked, onClick is triggered and the onepixel p1 p2 is output. this indicates that this in onClick is changed to the obj object by bind. In order to have a deep understanding of bind, let's take a look at the bind polyfill implementation:

If (! Function. prototype. bind) {Function. prototype. bind = function (oThis) {var parts GS = Array. prototype. slice. call (arguments, 1), fToBind = this, // this points to the target function fBound = function () {return fToBind. apply (// If var obj = new fBound () is executed externally, obj will be used as the final this and oThis this instanceof fToBind? This // this Is The new obj: oThis | this, // If the passed oThis is invalid, use the fBound caller as this // merge the parameters passed through bind and the parameters passed during the call, and pass them as the final parameters to the callback Gs. concat (Array. prototype. slice. call (arguments) ;}; // copy the prototype object of the target function to the new function, because the target function may be used as a constructor to use fBound. prototype = this. prototype; // return the reference of fBond. return fBound is called externally on demand ;};}

Application Scenario 1:Inheritance

As you know, JavaScript does not contain extend keywords in advanced languages such as Java and C #. Therefore, JavaScript does not have the concept of inheritance. If inheritance is required, call and apply can implement this function:

function Animal(name,weight){  this.name = name;  this.weight = weight;}function Cat(){  Animal.call(this,'cat','50'); //Animal.apply(this,['cat','50']);  this.say = function(){   console.log("I am " + this.name+",my weight is " + this.weight);  }}var cat = new Cat();cat.say();//I am cat,my weight is 50

When cat is generated through the new operator, this in Cat points to the cat object (for details about the new operator, refer to: http://www.cnblogs.com/onepixel/p/5043523.html ), the key to inheritance is that Animal is executed in Cat. call (this, 'cat', '50'). In call, this is passed as the thisArgs parameter, so this in the Animal method points to this in cat, this in cat points to cat objects, so this in Animal points to cat objects. Defining the name and weight attributes in Animal is equivalent to defining these attributes in cat, therefore, the cat object has the attributes defined in Animal to achieve the purpose of inheritance.

Application Scenario 2:Ripple

Before talking about the following content, let's first get to know a non-standard term in JavaScript: ArrayLike (class array/pseudo array)

The ArrayLike object is a part of the behavior of an array, which has long been expressed in DOM. The rise of jQuery makes ArrayLike shine brightly in JavaScript. The ArrayLike object is similar to the JS native Array, but it is built freely. It comes from developers' extensions to JavaScript objects, that is, prototype) we can define it freely without polluting the native Array of JS.

ArrayLike objects are widely used in JS. For example, the NodeList in DOM and the arguments in the function are all class array objects. These objects store every element like arrays, but they do not have the method to operate arrays, however, we can use call to 'move some methods of the array' to the ArrayLike object to perform operations on its elements. For example, we can traverse the arguments in the function as follows:

Function test () {// checks whether arguments is an Array instance console. log (arguments instanceof Array, // false Array. isArray (arguments) // false); // checks whether arguments has the forEach method console. log (arguments. forEach); // undefined // apply the forEach in the Array to the arguments Array. prototype. forEach. call (arguments, function (item) {console. log (item); // 1 2 3 4});} test (1, 2, 3, 4 );

In addition, we mentioned a unique feature of apply, that is, apply receives an array and transmits it to the parameter list when it is passed to the called function. This feature makes apply look better than call. For example, in a scenario where an array [1, 3, 4, 7] is given and the maximum element in the array is obtained. You know, the array does not have a method to obtain the maximum value. Generally, you need to write code to implement this. We know that there is a method in the Math object to obtain the maximum value, that is, Math. max (). The max method needs to pass a list of parameters and then return the maximum value among these parameters. Apply not only applies the max method of the Math object to other objects, but also converts an array into a parameter list and passes it to max. You can see the code at a Glance:

var arr = [2,3,1,5,4];Math.max.apply(null,arr); // 5

The above are several typical application scenarios of call and apply. Mastering these skills and applying these features to your actual project will make your code look more intriguing!

Articles you may be interested in:
  • Js apply/call/caller/callee/bind usage and Difference Analysis
  • Comparison and Analysis of call, apply, and bind usage in javascript
  • Usage of call (), apply (), and bind () in javascript
  • Enable the usage of apply, call, and bind in Javascript
  • Learn how to call (), apply (), bind () and callback in javascript.
  • Usage of call (), apply (), and bind () 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.