This in JavaScript using the detailed _javascript tips

Source: Internet
Author: User

Actually this is a cliché question. About this article is very many, in fact, I thought I had already understood it, but yesterday in the process of doing the project, or appeared a trace of doubt, think about before the JavaScript weekly in the collection to see a detailed this article (after the link, Also attached to the Chinese translation of rare earths) and another article recommended by a predecessor, they looked at it, the understanding of this has indeed improved a little.

The ' This ' in JavaScript is dynamic and is determined when the function is run, rather than in the function declaration. All functions can call ' this ', and there is no reference to whether the function belongs to an object. About this, there are mainly the following four kinds of situations.

1. The method being used as an object is called

If the function is a method of being treated as an object, then the This function is pointing to the object;

  var john = {
   firstName: "John"
  }
  function func () {
   alert (this.firstname + ": hi!")
  }
  John.sayhi = func
  john.sayhi ()//this = John

One thing to note here is that when an object's method is fetched to assign to a variable, the method becomes a function trigger, this points to window or underfind (strict mode).

2. Call within function

When there is this in the function, it means that it is called as a method call, which is the equivalent of the method that treats him as a window object, this points to window, and it is worth noting that ES5 is in fact this=undefined. Most browsers are still in accordance with the old method of implementation (I in the latest version of the Chrome,safari,firefox test all point to Window (201607)), in Firefox under the use of strict mode to point to undefined;

  Func ()
  function func () {
    alert (this)//[object Window] or [object global] or kind of..
  }

In order to pass this, () it should be a reference type, similar to OBJ.A or obj[' a ', and cannot be anything else.

There is also a small pit where the function is actually fired as a function mode when the object's method still exists, so the this defaults to window (strictly mode undefined) solution is to bind this to the function.

var numbers = { 
  Numbera:5,
  numberb:10,
  sum:function () {
   Console.log (this = = numbers);//=> True
   function calculate () {
    //This is Windows or undefined in strict mode
    console.log (this = = numbers);//=> FAL SE return
    this.numbera + this.numberb;
   }
   return calculate ();
  }
;
Numbers.sum (); => NaN or throws TypeError in strict mode 
var numbers = { 
  Numbera:5, numberb:10
  ,
  sum:function  () {
   Console.log (this = = numbers);//=> true
   function calculate () {
    Console.log (this = = numbers);// => true return
    This.numbera + this.numberb;
   }
   Use, call () method to modify the "context return
   Calculate.call" (this);
Numbers.sum (); => 15 

3. Call in New

A variable that refers to an object actually holds a reference to that object, which means that the variable actually holds a pointer to the real data.
When using the new keyword This change actually has the following steps:

Create this = {}.
You may change this in the execution of new, and then add properties and methods;
Returns the changed this.

  function Animal (name) {
    this.name = name
    This.canwalk = True
  }
  var Animal = new Animal ("Beastie")
  Alert (Animal.name)

Note that if the constructor returns an object, then this points to the returned object;

  function Animal () {
    this.name = ' Mousie ';
    This.age = ' n ';
    return {
      name: ' Godzilla '
    }//<--'ll be returned
  }

  var animal = new Animal ()
  Console.log (A Nimal.name)//Godzilla
  Console.log (animal.age)//undefined

Notice here that you don't forget to use new, or you won't create a new function. Instead of just executing a function, which is equivalent to a function call, this actually points to window

function Vehicle (type, wheelscount) { 
 this.type = type;
 This.wheelscount = Wheelscount;
 return this;
}
Function invocation
var car = Vehicle (' car ', 4); 
Car.type;    => ' car ' 
car.wheelscount//=> 4 car 
= = window//=> True

4. Explicitly invoke this, using call and apply

This is the most JavaScript-specific place.
The following code:

func.call(obj, arg1, arg2,...)

The first parameter will act as the object of this, and the subsequent argument will be used as a parameter to the function, and the solution is to use bind.

function Animal (type, legs) { 
 this.type = type;
 This.legs = legs; 
 This.loginfo = function () {
  Console.log (this = = Mycat);//=> true
  console.log (' the ' + This.type + ' has ' + This.legs + ' legs ');}
var mycat = new Animal (' Cat ', 4); 
Logs "The Cat has 4 legs"
settimeout (MyCat.logInfo.bind (Mycat), 1000); 
SetTimeout??
 var john = {
  firstName: "John",
  surname: "Smith"
 }
 function Func (A, b) {
  alert (This[a] + ' + t HIS[B])
 }
 Func.call (John, ' FirstName ', ' surname ')//"John Smith"

As for apply, it's just passing in the arguments in the array, and the other parts are the same, as follows:

 Func.call (John, ' FirstName ', ' surname ')
 func.apply (John, [' FirstName ', ' surname '])

They can also be used in class inheritance in ES5 to invoke the parent constructor.

  function Runner (name) { 
   Console.log (this instanceof Rabbit);//=> true
   this.name = name;
  function Rabbit (name, Countlegs) { 
   Console.log (this instanceof Rabbit);//=> true
   //indirect call, calling the parent constructor
   Runner.call (this, name);
   This.countlegs = Countlegs;
  }
  var myrabbit = new Rabbit (' White Rabbit ', 4); 
  Myrabbit; {name: ' White Rabbit ', countlegs:4}

5..bind ()

Comparison method. Apply () and. Call (), both of which perform the function immediately, while the. bind () function returns a new method that binds the predefined this and can be deferred.

The. Bind () method is to create a new function that, when executed, is the first parameter passed by. Bind (), which allows the creation of a function that is set up beforehand.

var numbers = { 
 array: [3, 5, ten],
 getnumbers:function () {return
  this.array;  
 }
};
Create a bound function
var boundgetnumbers = numbers.getNumbers.bind (numbers); 
Boundgetnumbers (); => [3, 5,] 
//Extract method from Object
var simplegetnumbers = numbers.getnumbers; 
Simplegetnumbers (); => undefined or throws an error in strict mode 

When using. bind (), it should be noted that. bind () creates an immutable context chain that is not modifiable. A binding function that uses. Call () or. Apply () is passed into a different context and does not change the context in which it was previously connected, and rebind does not work.

The binding function can change the context only when the constructor is called, but this is not a particularly recommended practice.

6. Arrow function

The arrow function does not create the context in which it executes itself, so that this depends on its external function when it is defined.

The arrow function cannot be changed once the context is bound, even if the method of context change is used:

  var numbers = [1, 2]; 
  (function () { 
   var get = () => {
    Console.log (this = = numbers);//=> true return this
    ;
   };
   Console.log (This = = numbers); => true Get
   ();//=> [1, 2]
   //arrow functions use. apply () and. Call ()
   Get.call ([0]);//=> [1, 2]
   GET.APPL Y ([0]); => [1, 2]
   //Bind
   Get.bind ([0]) ();//=> [1, 2]
  }). Call (numbers);

This is because the arrow functions have a static context and are not changed because of different invocations. So do not use arrow functions to define methods

function Period (hours, minutes) { 
   this.hours = hours;
   This.minutes = minutes;
  }
  Period.prototype.format = () => { 
   Console.log (this = = window);//=> true return
   this.hours + ' hours and ' + this.minutes + ' minutes ';
  };
  var walkperiod = new Period (2); 
  Walkperiod.format (); => ' undefined hours and undefined minutes '

Reference

Four scents of "this"

Gentle explanation of ' this ' keyword in JavaScript

JavaScript this riddle (translated)

It is highly recommended that students who do not understand the above three articles, of which the third is the second translation. If you have any questions about this, you are also welcome to discuss, exchange and promote thinking and common progress.

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.