Topsy-JavaScript this usage

Source: Internet
Author: User

JavaScript is a dynamic language that must be mastered in Web projects, and JavaScript-based frameworks are largely inseparable from the use and rationale of the most basic JavaScript. This article is mainly to summarize the evil of the this keyword in JavaScript.

To go straight to the point, throw an idea:"this in JavaScript is always pointing to the object that called it." Here I will give 3 most representative examples to verify my view.

example One object method call
    var x = 1;   function  testthis () {console.log (this. x); }      Testthis (); // this declares a global variable x, a global method, both of which are bound to the window, so when the result of running Testthis () is to take the X member on the Window object, the result is 1 var o== 5= testthis;     O.method (); // at this point, we say that the O object's method points to testthis, when it is called, this points to call his object, which is X is to go to the O object X, the result is 5  

This example is very basic, that is, the common object invocation method, the method inside this is to call him or to have his object

example two constructor creation
    varx = 2; functionTest () { This. x = 1; }varn \Newtest ();  Console.log (o.x); //1//This is the constructor in JavaScript, creating an instance with new, where the value is the X bound to the object o, so it's 1 .//The following example is a service in angular, you can directly understand that he will pass the second argument to the new singleton objectApp.service ("MyService",function($http, $modal) { This. Test =function() {Console.log ( This);          Test2 (); }                     functiontest2 () {Console.log ( This)}} myservice.test ()//Print MyService {test:function} and Window {}

Here log Out although test2 () can be called by test1 (), but it does not belong to the service, so if test2 inside call this, there will be common errors, oh mom ah, how can not adjust their methods?!

This example is often found in our project, and it is difficult to explain, as someone has asked me why the controller does not directly use this, but to use $scope to bind methods and variables, of course, this can replace some $scope, But inevitably encounter a series of problems caused by this context. The key to this problem is that the Test2 method does not belong to the object service, but because in the service closure (closure), he can be called by the service, so test2 inside this is not point to service, The other methods within the service are then called to error.

example Three change this point
  function  Test () {Console.log (this. x);  }  var o== 1= test; O.m.apply ({x:5});  // 5    O.m.call ()             ///  undefined// by Apply/call to specify the This action context of the calling function, Refers to a function that invokes an O object with a Parameter object, and the default parameter is the global

In fact, by this example, you can already see that the point of this is indeterminate, this value is determined when it enters the context, and remains constant during the context run. The above example changes the context of this, resulting in two inconsistent results and is the best evidence.

finally

The best part of this article is that if you read this article you can understand why this is sometimes not the same as what you expect, and you can get a solution to avoid such problems, then my goal is achieved. Fortunately you can see here, the solution is presented to you: just like angular to provide you with a $scope to bind properties and methods, like Coffeescript at the beginning of the object has such an assignment "_this = This", In our own JS practice, it may be useful to define "val self = This", and then use self to manipulate the properties of the object in the subsequent scope, which is the solution.

Topsy-JavaScript this usage

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.