About JS in this direction of the understanding of the summary!

Source: Internet
Author: User
Tags setinterval

about JS In this point of understanding!

What is this?
Definition: This is the object to which the function that contains it belongs when the method is invoked.

The first thing to say is thatthe point of this is not deterministic at the time of the function definition, but only when the function is executed can you determine who the this is pointing to, and actually this is the object that called it ( Although in many cases it would not be a problem to understand, but in fact that understanding is somewhat accurate, then I will go into this question in depth.

Example 1:

function A () {    var user = "Xiaoming";    //undefined    //window} A ();

As we said above, this finally points to the object that called it, where function A is actually being ordered by the Window object, and the following code can prove it.

function A () {    var user = "Xiaoming";    //undefined    Console.log (this); //window} WINDOW.A ();

Example 2:

var o = {    User: "Xiaoming",    fn:function () {        console.log (this.user);  //Xiaoming    }} O.fn ();

Here the this point is the object o, because you call this FN is executed through O.FN (), the natural point is that the object o,this is the point of the function creation is not the decision, when the call to decide, who calls the point to WHO.

If you want to understand this thoroughly, you have to look at the next few examples

Example 3:

var o = {    User: "Xiaoming",    fn:function () {        ///Xiaoming    }}window.o.fn ();

This code and the above code is almost the same, but here is why this is not pointing to the window, if according to the above theory, the end of this point is to call its object, here first to say a digression, window is the global object in JS, The variable we created actually adds a property to the window, so you can use the window point O object.

Here's why the above code does not point to window, so let's look at a piece of code.

var o = {    a:10,     b:{        a:12,        fn:function () {            //12        }    }}o.b.fn ();

Here is also the object o point out, but the same this does not execute it, then you will certainly say that I started to say that those are not all wrong? In fact, is not, just at the beginning of the inaccurate, I will add a word, I believe you can thoroughly understand this point of the problem.

  Case 1: If there is this in a function, but it is not called by the object above, then this point is the window, it is necessary to explain that in the strict version of JS this point is not the window.

  Scenario 2: If a function has this, the function is called by the object above, then this is the object at the top level.

  Case 3: If a function has this, the function contains multiple objects, although the function is called by the outermost object, this point is only the object of its upper level, example 3 can be proved.
Let's continue with a few examples.

var o = {    a:10,    b:{        //A:12,        fn:function () {            //undefined        }    }}o.b.fn ();

Although there is no attribute a in object B, this is also object B, because this only points to its upper-level object, regardless of whether there is anything in this object.

There is a more special case, example 4:

var o = {    a:10,    b:{        a:12,        fn:function () {            //undefined            //window        }    }} var j = o.b.fn;j ();

Here this is pointing to window, which is also very important "thisis always pointing to the last object to invoke it ", that is, when it is executed by who is called, Example 4, although the function fn is referenced by the object B, However, when the FN is assigned to the variable j is not executed, so the final point is the window, which is not the same as the example 3, example 3 is the direct execution of FN.

 

constructor Version of this:
function Fn () {    ///Xiaoming

The reason why object A can point out the function fn inside the user is because the New keyword can change the direction of this, understand this sentence can think of our example 3, we here with the variable A to create an instance of FN (equivalent to copy the FN into object a), at this time just create, is not executed, and the call to the function FN is object A, then this point is the natural object A, then why there is user in object A, because you have copied an FN function into object A, using the New keyword is equivalent to copying a copy.

when this encounters a return
function fn ()  {      this.user = ' xiaoming ';      return {};  } var a = new Fn;  //undefined
function fn ()  {      this.user = ' xiaoming ';      return function () {};} var a = new Fn;  Console.log (A.user); //undefined
function fn ()  {      this.user = ' xiaoming ';      return 1;} var a = new Fn;  //Xiaoming
function fn ()  {      this.user = ' xiaoming ';      return undefined;} var a = new Fn;  //Xiaoming

From these examples it can be concluded that if the return value is an object, then this is the object returned, if the return value is not an object then this is an instance of the function.

function fn ()  {      this.user = ' xiaoming ';      return undefined;} var a = new Fn;  //fn {User: "Xiaoming"}

In special cases, NULL is also an object, but here this is an instance of the function.

function fn ()  {      this.user = ' xiaoming ';      return null;} var a = new Fn;  //Xiaoming

When this encounters the call , apply, bind method

1. Call ()

  

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = A.fn;b.call (a);

By the call method, the first parameter is added to which environment to add B to, in a nutshell, this will point to that object.

The call method can add multiple parameters in addition to the first argument, as follows:

var a = {    User: "Xiaoming",    fn:function (e,ee) {        //xiaoming        //3    }}var b = A.fn; B.call (a,1,2);

2. Apply ()

The Apply method is somewhat similar to the call method, and it can also change the point of this

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = a.fn;b.apply (a);

The same applies can have multiple parameters, but the difference is that the second parameter must be an array, as follows:

var a = {    User: "Xiaoming",    fn:function (e,ee) {        //xiaoming        //11    }}var b = a.fn;b.apply (a,[10,1]);

Note If the first argument to call and apply is NULL, then this refers to the Window object

var a = {    User: "Xiaoming",    fn:function () {        //window {external:object, chrome:object, Document:document, A:object, Speechsynthesis:speechsynthesis ...}}    var b = a.fn;b.apply (null);

3. Bind ()

The Bind method is somewhat different from the call and apply methods, but they can be used to change the point of this anyway.

Let's talk about their differences first.

var a = {    User: "Xiaoming",    fn:function () {        console.log (this.user);    }} var B = A.fn;b.bind (a);

We found that the code was not printed, yes, that's the difference between bind and call, the Apply method, and the Bind method actually returns a modified function.

var a = {    User: "Xiaoming",    fn:function () {        console.log (this.user);    //function () {[native code]}

So let's run the function C and see if we can print out the user in object A.

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = A.fn;var c = B.bind (a); C ();

Summary: Call and apply are changes in the context of this and immediately execute this function, the bind method can let the corresponding function when it is called when the calling, and the parameters can be added at the time of execution, this is their difference, according to their actual situation to choose to use.

What is this?
Definition: This is the object to which the function that contains it belongs when the method is invoked.

The first thing to say is thatthe point of this is not deterministic at the time of the function definition, but only when the function is executed can you determine who the this is pointing to, and actually this is the object that called it ( Although in many cases it would not be a problem to understand, but in fact that understanding is somewhat accurate, then I will go into this question in depth.

Example 1:

function A () {    var user = "Xiaoming";    //undefined    //window} A ();

As we said above, this finally points to the object that called it, where function A is actually being ordered by the Window object, and the following code can prove it.

function A () {    var user = "Xiaoming";    //undefined    Console.log (this); //window} WINDOW.A ();

Example 2:

var o = {    User: "Xiaoming",    fn:function () {        console.log (this.user);  //Xiaoming    }} O.fn ();

Here the this point is the object o, because you call this FN is executed through O.FN (), the natural point is that the object o,this is the point of the function creation is not the decision, when the call to decide, who calls the point to WHO.

If you want to understand this thoroughly, you have to look at the next few examples

Example 3:

var o = {    User: "Xiaoming",    fn:function () {        ///Xiaoming    }}window.o.fn ();

This code and the above code is almost the same, but here is why this is not pointing to the window, if according to the above theory, the end of this point is to call its object, here first to say a digression, window is the global object in JS, The variable we created actually adds a property to the window, so you can use the window point O object.

Here's why the above code does not point to window, so let's look at a piece of code.

var o = {    a:10,     b:{        a:12,        fn:function () {            //12        }    }}o.b.fn ();

Here is also the object o point out, but the same this does not execute it, then you will certainly say that I started to say that those are not all wrong? In fact, is not, just at the beginning of the inaccurate, I will add a word, I believe you can thoroughly understand this point of the problem.

  Case 1: If there is this in a function, but it is not called by the object above, then this point is the window, it is necessary to explain that in the strict version of JS this point is not the window.

  Scenario 2: If a function has this, the function is called by the object above, then this is the object at the top level.

  Case 3: If a function has this, the function contains multiple objects, although the function is called by the outermost object, this point is only the object of its upper level, example 3 can be proved.
Let's continue with a few examples.

var o = {    a:10,    b:{        //A:12,        fn:function () {            //undefined        }    }}o.b.fn () ;

Although there is no attribute a in object B, this is also object B, because this only points to its upper-level object, regardless of whether there is anything in this object.

There is a more special case, example 4:

var o = {    a:10,    b:{        a:12,        fn:function () {            //undefined            //window        }    }} var j = o.b.fn;j ();

Here this is pointing to window, which is also very important "thisis always pointing to the last object to invoke it ", that is, when it is executed by who is called, Example 4, although the function fn is referenced by the object B, However, when the FN is assigned to the variable j is not executed, so the final point is the window, which is not the same as the example 3, example 3 is the direct execution of FN.

 

constructor Version of this:
function Fn () {    ///Xiaoming

The reason why object A can point out the function fn inside the user is because the New keyword can change the direction of this, understand this sentence can think of our example 3, we here with the variable A to create an instance of FN (equivalent to copy the FN into object a), at this time just create, is not executed, and the call to the function FN is object A, then this point is the natural object A, then why there is user in object A, because you have copied an FN function into object A, using the New keyword is equivalent to copying a copy.

when this encounters a return
function fn ()  {      this.user = ' xiaoming ';      return {};  } var a = new Fn;  //undefined
function fn ()  {      this.user = ' xiaoming ';      return function () {};} var a = new Fn;  Console.log (A.user); //undefined
function fn ()  {      this.user = ' xiaoming ';      return 1;} var a = new Fn;  //Xiaoming
function fn ()  {      this.user = ' xiaoming ';      return undefined;} var a = new Fn;  //Xiaoming

From these examples it can be concluded that if the return value is an object, then this is the object returned, if the return value is not an object then this is an instance of the function.

function fn ()  {      this.user = ' xiaoming ';      return undefined;} var a = new Fn;  //fn {User: "Xiaoming"}

In special cases, NULL is also an object, but here this is an instance of the function.

function fn ()  {      this.user = ' xiaoming ';      return null;} var a = new Fn;  //Xiaoming

When this encounters the call , apply, bind method

1. Call ()

  

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = A.fn;b.call (a);

By the call method, the first parameter is added to which environment to add B to, in a nutshell, this will point to that object.

The call method can add multiple parameters in addition to the first argument, as follows:

var a = {    User: "Xiaoming",    fn:function (e,ee) {        //xiaoming        //3    }}var b = A.fn;b.call (A , for each);

2. Apply ()

The Apply method is somewhat similar to the call method, and it can also change the point of this

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = a.fn;b.apply (a);

The same applies can have multiple parameters, but the difference is that the second parameter must be an array, as follows:

var a = {    User: "Xiaoming",    fn:function (e,ee) {        //xiaoming        //11    }}var b = a.fn;b.apply (a,[ 10,1]);

Note If the first argument to call and apply is NULL, then this refers to the Window object

var a = {    User: "Xiaoming",    fn:function () {        //window {external:object, chrome:object, Document:document, a : Object, Speechsynthesis:speechsynthesis ...}}    var b = a.fn;b.apply (null);

3. Bind ()

The Bind method is somewhat different from the call and apply methods, but they can be used to change the point of this anyway.

Let's talk about their differences first.

var a = {    User: "Xiaoming",    fn:function () {        console.log (this.user);    }} var B = A.fn;b.bind (a);

We found that the code was not printed, yes, that's the difference between bind and call, the Apply method, and the Bind method actually returns a modified function.

var a = {    User: "Xiaoming",    fn:function () {        console.log (this.user);    //function () {[native code]}

So let's run the function C and see if we can print out the user in object A.

var a = {    User: "Xiaoming",    fn:function () {        ///xiaoming    }}var b = A.fn;var c = B.bind (a); C ();

Summary: Call and apply are changes in the context of this and immediately execute this function, the bind method can let the corresponding function when it is called when the calling, and the parameters can be added at the time of execution, this is their difference, according to their actual situation to choose to use.

the JavaScript timer and the this point in the arrow functions

Using the timer in JS (setinterval,settimeout), it is easy to encounter this point of the problem.

Directly on the example:

  var name = ' My name is window ';  var obj = {      name: ' My name is obj ',      fn:function () {          var timer = null;          Clearinterval (timer);          Timer = setinterval (function () {              console.log (this.name); My name is Window          }, +)     }}

Here, you can see from this.name that this is pointing to window.

If there are no special pointers, the setinterval and settimeout callback functions in this direction are window. This is because the JS timer method is defined under window. However, in a lot of scenarios, you need to change the direction of this. Here is a summary of several:

1. The most common method: to save this as a variable in an external function, use the variable in the callback function instead of using this directly.

  var name = ' My name is window ';  var obj = {      name: ' My name is obj ',      fn:function () {          var. = this;          var timer = null;          Clearinterval (timer);          Timer = setinterval (function () {              console.log (that.name);   My name is obj         }, +)     }}

var is added to fn = this; Use this instead of this in the callback function. This method is the most common and most widely used.

2, using the Bind () method (Bind () to ES5 standard, low version IE has compatibility problems, can be introduced es5-shim.js resolution)

Bind () acts like call and apply, both of which modify this point. But call and apply is to modify this point after the function executes immediately, and bind returns a new function that creates a new function with the same body as the original function, and this in the new function points to the incoming object.

  var name = ' My name is window ';  var obj = {      name: ' My name is obj ',      fn:function () {          var timer = null;          Clearinterval (timer);          Timer = setinterval (function () {              console.log (this.name);   My name is obj          }.bind (this), +)     }}

Here's why you can't use call and apply because call and apply are not returning functions, they are executing functions immediately, so you lose the function of the timer.

3. Use the arrow function of ES6: The maximum function of the arrow function is this point.

  var name = ' My name is window ';  var obj = {      name: ' My name is obj ',      fn:function () {          var timer = null;          Clearinterval (timer);          Timer = SetInterval (() = {              Console.log (this.name);  My name is obj          }, +)     }}

The arrow function does not have its own this, and its this inherits from the scope of the outer function. So, in this case, the this in the timer callback function is the this that inherits the FN. Of course, the arrow function also has a compatibility problem, if compatible with the low version of IE, need to use Babel compilation.

What do you mean?

If the return value is an object, then this is the object that is returned, and if the return value is not an object then this is an instance of the function.

About JS in this direction of the understanding of the summary!

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.