JavaScript's this pointer in-depth explanation

Source: Internet
Author: User

This meaning in JavaScript is very rich, it can be a global object, the current object or any object, depending on how the function is called. Functions are called as Object method calls, as function calls, as constructor calls, apply, or call.

Object Method Invocation

This is bound to the object when it is called as an object method.

var point = {  x:0,  y:0,  moveto:function (x, y) {      this.x = this.x + x;      This.y = This.y + y;      }  };  Point.moveto (1, 1)//this bind to the current object, which is the point object

Here I would like to emphasize that this is when the function executes to get the corresponding value, not the function definition. Even an object method call, if the function property of the method is passed into another scope as a function name, also changes the point of this. Let me give you an example:

var a = {aa:0,bb:0,fun:function (x, y) {This.aa = This.aa + x;this.bb = this.bb + y;}}; var AA = 1;var B = {aa:0,bb:0,fun:function () {return THIS.AA;}} A.fun (3,2);d ocument.write (A.AA);//3,this points to the object itself document.write (B.fun ());//0,this points to the object itself (function (AA) {//Note the functions are passed in, Instead of the result of the function execution, var c = AA ();d ocument.write (c);//1, because the fun is executed in that place, which causes this to no longer point to the object itself, but the window here}) (B.fun);

That makes sense. This is an easy place to confuse.

Function call

Functions can also be called directly, this time this is bound to the global object.

var x = 1;  function test () {this.x = 0;  } test (); alert (x); 0

However, there are some problems, that is, the function defined inside the function, the This also points to the global, and we hope the opposite. The code is as follows:

var point = {  x:0,  y:0,  moveto:function (x, y) {      //internal function     var MoveX = function (x) {      this.x = x ;//this bound to Global    };     Intrinsic    var movey = function (y) {     this.y = y;//this bound to global    };     MoveX (x);     Movey (y);     }  };  Point.moveto (1, 1);  Point.x; ==>0  point.y;//==>0  x;//==>1  y;//==>1

We will find that not only do we want to move the effect is not completed, but will be more than two global variables. So how to solve it? Whenever you want to enter a function in a function, save this to a variable, and then use that variable. The code is as follows:

var point = {  x:0,  y:0,  moveto:function (x, y) {       var. = this;      Intrinsic     var MoveX = function (x) {      that.x = x;      };      Intrinsic     var movey = function (y) {      that.y = y;      }      MoveX (x);      Movey (y);      }  };  Point.moveto (1, 1);  Point.x; ==>1  Point.y;//==>1
Constructor call

You can use this to point to the newly created object when you create the constructor yourself in JavaScript. This prevents the this in the function from pointing to the global.

var x = 2;  function test () {this.x = 1;  } var o = new Test (); alert (x); 2
Apply or call calls

These two methods can toggle the context in which the function executes, that is, the object that changes this binding. Apply and call are similar, except that one requirement is an array when passing in parameters, and one requirement is to be passed in separately. So let's take the example of apply:

<pre name= "code" class= "html" >var name = "Window"; var someone = {    name: "Bob",    showname:function () {        alert (this.name);}    }; var other = {    name: "Tom"};   Someone.showname ();//bobsomeone.showname.apply ();    Windowsomeone.showName.apply (other);    Tom

As you can see, when you access the method in the object normally, this points to the object. When apply is used, the current object of this is global, and when apply has parameters, this is the current object of this parameter.

Arrow function call

One thing to add here is that the this of the arrow functions in the next generation of JavaScript standard ES6 always points to this when the function is defined, not when it is executed. We use an example to understand:

var o = {    x:1,    func:function () {Console.log (this.x)},    test:function () {        setTimeout (function () { C12/>this.func ();        },    }};o. Test (); TypeError:this.func is not a function

The above code will cause an error because the point of this is changed from O to Global. We need to modify the above code as follows:

var o = {    x:1,    func:function () {Console.log (this.x)},    test:function () {        var _this = this;        SetTimeout (function () {            _this.func ();         },}};o);    Test ();

This is done by using the externally saved this. Here we can take advantage of the arrow function, as we have just said, the arrow function of this always points to the function definition when the this, rather than when executing. So we'll modify the code as follows:

var o = {    x:1,    func:function () {Console.log (this.x)},    test:function () {        setTimeout (() = {th Is.func ()},    }};o. Test ();

This time this is pointing to O, and we need to note that this is not going to change the point of the object, we know that call and apply can change the point of this, but in the arrow function is not valid.

var x = 1,    o = {        x:10,        test: () = This.x    };o.test ();//1o.test.call (o);//Still 1

This makes it possible to understand the difference between this binding object in various situations.

JavaScript's this pointer in-depth explanation

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.