This, call, apply in JavaScript and their usage and differences are described in detail. javascriptapply

Source: Internet
Author: User

This, call, apply in JavaScript and their usage and differences are described in detail. javascriptapply

Learning cause:

In the previous JavaScript study, this, call, and apply are always confusing to me, but they are widely used. It took a special day to understand JavaScript's this, call, and apply.

There are also a lot of books to be referenced in the middle, mainly based on JavaScript design patterns and development practices, supplemented by JavaScript advanced programming and JavaScript that you don't know. These three books are of great help to me in understanding this, call, and apply.

This

First, let's talk about this first.

In the description of this in JavaScript design patterns and development practices, I think this is the core point of a sentence. That is:

This in JavaScript always points to an object.
In actual application, this can be divided into the following four types:

  1. Method call as an object
  2. Called as a common function
  3. Constructor call
  4. Apply and call

Next we will analyze the first three points. For the apply and call calls at, we will explain them in detail in the call and apply sections.

1. method call as an object

Note: When called as an object method, this points to this object.
Example:

/*** 1. When calling an object method **, this points to this object. */Var obj = {a: 1, getA: function () {console. log (this = obj); console. log (this. a) ;}}; obj. getA (); // true, 1

2. As a common function call

Note: When called as a common function, this always points to a global object (window in the browser ).
Example:

/*** 2. this is called as a common function. ** this must point to an object when it is not called as an object property. This is a global object. */Window. name = 'globalname'; var getName = function () {console. log (this. name) ;}; getName (); // 'globalname' var myObject = {name: "ObjectName", getName: function () {console. log (this. name) }}; myObject. getName (); // 'objectname' // The function () {console. log (this. name)} // This sentence is assigned to theName. ThisName is called in a global object. It naturally reads the name value of the Global Object var theName = myObject. getName; theName (); // 'globalname'

3. constructor call

Note: When called as a constructor, this points to the returned object.
Example:

/*** 3. When calling as a constructor ** as a constructor call, this points to the returned object. */Var myClass = function () {this. name = "Lxxyx" ;}; var obj = new myClass (); console. log (obj. name); // Lxxyxconsole. log (obj) // myClass {name: "Lxxyx "}

However, if other return objects are manually specified in the constructor, this does not work.
If the return type is another data type, no problem occurs.

Var myClass = function () {this. name = "Lxxyx"; // when return is added, other objects are returned. This does not work. Return {name: "ReturnOthers" }}; var obj = new myClass (); console. log (obj. name); // ReturnOthers

4. Call and Apply

The Call and Apply functions are the same. Is used to specify the point of this in the function body.

Difference between Call and Apply

Call: the first parameter is the point of this. The parameters to be passed to the function must be input one by one.
Apply: the first parameter is the point of this, and the second parameter is an array. All parameters are input at one time.

If the first parameter is null, this indicates the call itself.

1. Change this point

Note: This is the most common use of call and apply. Used to change the point of this in the function body.
Example:

Var name = "GlobalName" var func = function () {console. log (this. name)}; func (); // "GlobalName" var obj = {name: "Lxxyx", getName: function () {console. log (this. name) }}; obj. getName. apply (window) // "GlobalName" directs this to windowfunc. apply (obj) // "Lxxyx" to point this to obj

2. Borrow methods from other objects

Here, we start with an anonymous function that is executed immediately:

(Function (a, B) {console. log (arguments) // 1, 2 // call the Array Prototype Method Array. prototype. push. call (arguments, 3); console. log (arguments) // 1, 2, 3}) (1, 2)

The function has the arguments attribute, while arguments is an array of classes.
However, arguments cannot directly call the Array method. Therefore, call or apply is used to call the prototype method of the Array object.
The principle is also easy to understand. For example, the push method is called just now, and the source code of the push method in Google's v8 engine is as follows:

Function ArrayPush () {var n = TO_UINT32 (this. length); // The length of the pushed object var m = % _ ArgumentsLength (); // The number of pushed parameters for (var I = 0; I <m; I ++) {this [I + n] = % _ Arguments (I); // copy element} this. length = n + m; // modify the return this attribute of length. length ;}

It is only related to this, so as long as it is a class array object, you can call the relevant method for processing.

This part of the content is complex, and it is not enough in addition to your own level. Therefore, we recommend that you purchase related books or wait for my blog post.

Feelings

By studying this part, we have deepened our understanding of JavaScript. The most intuitive manifestation is that when you look at the source code of some excellent frameworks, it is no longer blurred by this, call, apply, and bind. Very happy ~

For the next period of time, I am going to have a deep dive into the daily learning and usage of CSS. After all, JavaScript is learned, and HTML and CSS cannot be left behind.

Articles you may be interested in:
  • This points to a problem after JavaScript call apply binds a JavaScript object to a DOM event.
  • Simple comparison and analysis of the use of apply, call, and this in JavaScript
  • Apply, call, and this are the difficulties of Javascript technology.

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.