The "This" keyword in __java javascript

Source: Internet
Author: User
1. The mystery of this

Most of the time this keyword is filled with mysterious colors for me and many JavaScript developers. This is a powerful feature, but it requires effort to be understood.

From Java, PHP, and other standard language backgrounds, in class methods, this is an instance of the current object, not much or less. In most cases, he cannot use it outside of the method, a simple strategy that does not cause confusion about this understanding.

Things are different in javascript: This is the execution environment for the current function (execution context of a funciton). JavaScript has 4 function calls: Function call: alert (' Hello World ') method call: Console.log (' Hello World ') constructor call: New RegExp (' \d ') Indirect call: Alert.call (Undefined, ' Hello world! ')

Each invocation method defines their own execution environment, so this is slightly different from what the developer expects.

In addition, the strict pattern also affects the execution context.

The key to understanding this keyword is that the function call has a clear view and how it affects the context.

The focus of the text is the interpretation of the call, how the function call affects this, and demonstrates the common pitfalls of identifying the context.

Before we begin, let's familiarize ourselves with some terms: the invocation of a function is the code that is executing the body of the function, or a simple call. For example, a parseint function call is a parseint (' ") called context that is the value of this in the function body. For example, the invocation of map.set (' key ', ' value ') has a call context map A function's scope is a collection of variables, objects, and functions that can be accessed in the function body. 2. Function call

function calls are executed when an expression that is evaluated on a function object is followed by an opening parenthesis (a comma-delimited list of argument expressions and a closing parenthesis). For example parseint (' 18 ')

A function call expression cannot be a property accessor (for example, Console.log (' Hi ')), it is a method call. Again for example [1,5].join (', ') is not a function call, but a method call. This distinction is very important.

A simple example of a function call:

function Hello (name) {return
    ' Hello ' + name + '! ';
}

The function calls the
var message = Hello (' world ');
Console.log (message);//=> ' Hello world! '

The above hello (' world ') is a function call: The hello expression is evaluated to a function object, followed by a pair of parentheses with the parameter ' world '

A more advanced example is Iife (immediately-invoked function expression):

var message = (function (name) {return  
   ' Hello ' + name + '! ';
}) (' World ');

Iife is also a function call: The first pair of parentheses (function (name) {...}) is an expression defined as a function, followed by a pair of parentheses with the parameter ' World ' 2.1. The this in a function call

In a function call, this is a global object

The global object is determined in the execution environment. In the browser, he is the window object

window;
function MyFunc () {
    console.log (window = = this);/true;
}

In a function call, the execution context is the global object.

Let's examine the context of the following function:

function sum (A, b) {
    Console.log (this = = window);/true
    this.mynumber = 20;///Add a property called ' MyNumber ' to the global object
    return a + B;
}
SUM () is called as
a function//This is a Global object (window) sum in sum ()
;        =>
window.mynumber;//=> 20

When sum (15, 16) is invoked, JavaScript automatically sets this as the global object, and in the browser it is window

This is also a global object when this is used outside of a function:

Console.log (this = = window); => true  
this.mystring = ' Hello world! ';  
Console.log (window.mystring); => ' Hello world! '  
<!--in a HTML file-->  
<script type= "Text/javascript" >  
   console.log (this = = window);//=> true< C10/></script>  
2.2. In the strict mode (strict mode), this in the function call

In strict mode (strict mode), in a function call, this is a undefined

Strict mode (strict mode) is introduced in ECMAScript 5.1, which is a finite variant of JavaScript. It provides better security and stronger error checking.

To enable strict mode (strict mode), place the instruction "use strict" at the top of the function body

Once enabled, strict mode (strict mode) affects the execution context so that it is not defined in a regular function call. The execution context is no longer a global object, as opposed to 2.1 above.

function MyFunc () {
    ' use strict ';
    Console.log (This = = undefined);//=>true
}
myFunc ();

Examples of functions that are executed in strict mode:

function Multiply (A, b) {  
    ' use strict ';//enable strict mode
    Console.log (this = = undefined);//=> true return
    A * b;
}
The value of this is undefined
multiply (2, 5);//=> 10  

Strict mode is not only effective in the current execution environment, but also in the internal function execution environment. This means that internal functions are also executed in strict mode.

function execute () {  
   ' use strict ';//Activate the strict mode    
   function concat (str1, str2) {
     //the Strict The mode is enabled too
     console.log (this = = undefined);//=> true return
     str1 + str2;
   }
   Concat () is invoked as a function in strict mode
   //The In concat () is undefined
   concat (' Hello ', ' world! ') ; => "Hello world!"
}
Execute ();  

A single JavaScript file may contain both a non strict pattern and a strict pattern. Therefore, there may be different contextual behavior in a single script of the same invocation type:

function Nonstrictsum (A, b) {  
  //non-strict mode
  console.log (this = = window);//=> true return
  A + b;
  
   
function Strictsum (A, b) {  
  ' use strict ';
  Strict mode boot
  console.log (this = = undefined);//=> true return
  A + b;
}
Within the Nonstrictsum function This is window
nonstrictsum (5, 6);///=>//  
strictsum function This is undefined
strictsum (8, 12); => 20  
  
2.3. Traps: This in internal functions Mistaken cognition: A common pitfall of function calls is to think ThisThe internal function is the same as the external function of the correct cognition: correctly, the context of the internal function depends only on the invocation, not on the context of the external function.
var numbers = {  
   Numbera:5,
   numberb:10,
   sum:function () {
     Console.log (this = = numbers);//=> True
  function calculate () {
       //This is window or undefined, if it is in strict mode.
       Console.log (This = = numbers);//=> false return
       This.numbera + this.numberb;
     }
     return calculate ();
   }
;
Numbers.sum (); => Normal mode Nan, in strict mode will be the error

To solve this problem, the Calculate function should be executed by the same execution context as the Sum method, which can be used to specify the execution contexts:

var numbers = {  
   Numbera:5,
   numberb:10,
   sum:function () {
     Console.log (this = = numbers);//=> Tru e
     function Calculate () {
       Console.log (this = = numbers);//=> true return
       This.numbera + this.numberb;
     }
     Use the. Call () method to modify the execution context return
     calculate.call (this);
Numbers.sum (); => 15
3. Method call

A method is a function stored in an object's properties. For example:

var myObject = {
    //Hellofunction It is a method
    hellofunction:function () {return
        ' Hello world! ';
    }
}

var message = Myobject.hellofunction ();

Hellofunction is a method of MyObject . Gets the method, using the property accessor: myobject.hellofunction.

The method call executes in an expression in the form of a property accessor that evaluates to a function object followed by an open parenthesis (a comma-delimited list of argument expressions and a closing parenthesis).

Recall the previous example, Myobject.hellofunction () is the Hellofunction method call on the object myObject. Method calls are also: [1,2]. Join (', ') or/\s/.test (' Beautiful World ').

It is important to separate function calls from method calls because they are of different types. The main difference is that the method call requires a property accessor to invoke the function (Obj.myfunc ()), and the function call does not need (MyFunc ()).

The following invocation list shows how to distinguish between them:

[' Hello ', ' World '].join (', '); Method call
({ten:function () {return 10;}}). Ten (); Method invokes
var obj = {};  
Obj.myfunction = function () {return  
  new Date (). toString ();
Obj.myfunction (); Method calls

var otherfunction = obj.myfunction;  
Otherfunction ();     function call
parsefloat (' 16.60 ');//Function call
isNaN (0);            Function call

Understanding differences in function calls and method calls can help us identify the correct context. 3.1. This in the method call

This is the object that owns the method in the method call

When a method is called in an object, this becomes the object itself.

var myObject = {
    mymethod:function () {this
        ;
    }
}
Myobject.mymethod ();

Let's create an object with a method that adds a number:

var calc = {
    num:0,
    increment:function () {
        Console.log (this = = Calc);//True
        This.num + 1;
        return this.num;
    }
;
Method calls
calc.increment ();//=> 1
calc.increment ();//=> 2

Call Calc.increment () to make the context of the Increment function a Calc object. So it's good to use This.num to add the number attribute.

Let's look at other situations. A JavaScript object inherits a method from its prototype. When this inherited method is invoked in this object, the context of the invocation is still itself.

var Mydog = object.create ({  
  sayname:function () {
     Console.log (this = = Mydog);//=> true return
     THIS.N ame;
  }
});
Mydog.name = ' Milo ';  
Method invocation. This is Mydog
mydog.sayname ();//=> ' Milo '
3.2. Traps: Separation methods and their objectsErroneous cognition: From an object's method can be extracted into a separate variable var alone = Myobj.mymethod. When the method is called individually, detach from the original object alone (), which you might consider to be the object that defines the method. Correct perception: If no object calls the method, a function call occurs: This is a global object window or undefined in strict mode (see 2.1 and 2.2)

The following example creates an animal constructor and creates an instance of it-mycat. Then Settimout () records the Mycat object information after 1 seconds:

function Animal (type, legs) {
  this.type = type;
  This.legs = legs;
  This.loginfo = function () {
    Console.log (this = = Mycat);//=> false
    Console.log (' the ' + This.type + ' has ' + This.legs + ' legs ');
  }
var mycat = new Animal (' Cat ', 4);  
Displays "The undefined has undefined legs" or throws an exception (in strict mode)
settimeout (mycat.loginfo, 1000); 
Displays "The Cat has 4 legs"
settimeout (MyCat.logInfo.bind (Mycat), 1000);  
4. Constructor call

When the new keyword is followed by an expression whose value is a function object, an open parenthesis (a comma-delimited list of argument expressions and a closing parenthesis), the constructor method call is executed. For example: New RegExp (' \ d ').

function Country (name, traveled) {  
   this.name = name? Name: ' United Kingdom ';
   this.traveled = Boolean (traveled);
}
Country.prototype.travel = function () {  
  this.traveled = true;
};
Constructor invokes
var France = new Country (' France ', false);  
The constructor invokes the
var unitedkingdom = new Country;

France.travel (); Travel in France

The new Country (' France ', false) is a constructor call to a Country function. The result of this execution is a new object whose name property is ' France '

If the constructor has no arguments, parentheses can be omitted: new Country 4.1. This in the constructor call

This is the newly created object in the constructor call

The context of the constructor call is the object that was just created. It is used to initialize the object's data, from constructor function parameters, to set initial property values, and some processing methods.

Functioin Constructor () {
    this;//itself object
}

var object = new Constructor ();//object is the same object as the above.

Let's take a look at the context of the following example:

function foo () {
    console.log (this instanceof foo);//=> true
    this.property = ' Default Value ';
}
Constructor calls
var fooinstance = new Foo ();
Fooinstance.property; => ' Default Value '

The new Foo () is called as a constructor, and its context is fooinstance. Inside Foo , the object is initialized:this.property is given a default value.

When new Foo () is executed, JavaScript creates an empty object and makes it the context of the constructor method. You can then use the This keyword to add attributes to the object: this.property = ' Default Value ' 4.2. Trap: Forget new

Some JavaScript functions create instances not only with constructors, but also by function calls. For example RegExp:

var reg1 = new RegExp (' \\w+ ');
var reg2 = RegExp (' \\w+ ');

REG1 instanceof RegExp;         => true
reg2 instanceof RegExp;         => true
Reg1.source = = = Reg2.source;    => true
function Vehicle (type, wheelscount) {
    if (!) ( This instanceof Vehicle) {
        throw error (' ERROR: Wrong call ');
    }
    This.type = type;
    This.wheelscount = Wheelscount;
    return this;
}

var car = new Vehicle (' car ', 4);
Car.type;
Car.wheelscount;
Car instanceof Vehicle;
Function call. Generates an error
var brokencar = Vehicle (' Broken Car ', 3);

The new Vehicle (' car ', 4) runs fine: A newer object is created and initialized because the new keyword exists in the constructor call 5. Indirect invocation

Indirect invocation : When a function is invoked with Myfun.call () or myfun.apply, an indirect call is performed.

A function in JavaScript is the first class object, which means that a function is an object. The type of this object is a Function.

Two methods of a function object:

Call (thisarg[, arg1[, arg2[, ...)]]
Apply (Thisarg, [Arg1, Arg2, ...])

For example:

Myfun.call (Thisvalue, ' val1 ', ' val2 ');
Myfunc.apply (Thisvalue, [' Val1 ', ' val2 ']);
5.1. This in the indirect call

Indirect calling This is the first parameter of . Call () or . Apply ()

The following example shows the context of an indirect invocation:

var rabbit = {name: ' Little White Rabbit '};  
function Concatname (string) {  
  Console.log (this = = rabbit);//=> true return
  string + this.name;
}
Indirect call
Concatname.call (rabbit, ' hello ');  => ' Hello little white Rabbit '  
concatname.apply (rabbit, [' goodbye ']);//=> ' Goodbye Bunny '  

Indirect invocation is useful at some point, such as in strict mode, when our context is window or undefined , using indirect invocation, this in the function body can be the object we want. 6. Binding Functions

A binding function is a function that carries an object. Typically, it is created by using the . bind () function from the original function. This method is used to change the execution environment of the function

function multiply (number) {  
  ' use strict ';
  return this * number;
}
Create a bound function with the context
var double = Multiply.bind (2);  
Invoke the bound function
double (3);  => 6  
double (ten);//=> 20  
6.1. This in the binding function

This is the first parameter of the . bind () function in the number of binding orders.

var numbers = {  
  array: [3, 5, ten],
  getnumbers:function () {return
    this.array;    
  }
};
Create a binding function
var boundgetnumbers = numbers.getNumbers.bind (numbers);  
Boundgetnumbers (); => [3, 5,]  
//Extract Method
var simplegetnumbers = numbers.getnumbers;  
Simplegetnumbers (); => undefined or throw an exception in strict mode
6.2. Tight Context Binding

. Bind () creates a permanent context link and always maintains it.

When using. Call () or. Apply () with a different context, the bound function cannot change the context of its link, or even the rebound has no effect. Only the constructor calls of the binding function can be changed, but this is not the recommended method (for a constructor call, use a normal, unbound function).

The following example creates an bound function and then attempts to change its predefined context:

function Getthis () {  
  ' use strict ';
  return this;
}
var one = Getthis.bind (1);  
The binding function calls one
();//=> 1  
//use. Apply (). Call () calls the binding function
One.call (2);  => 1  
one.apply (2);//=> 1  
//Again bind
One.bind (2) ();//=> 1  
//Call binding function through constructor

Only new () changes the context of the bound function, and other types of calls do not change the execution context of the function. 7. Arrow function

The arrow function is intended to declare a function in a shorter form and to bind the context in lexical terms.

It can be used in the following ways:

var hello = (name) => {return  
  ' hello ' + name;
};
Hello (' world '); => ' Hello world '  
///only reserved even
[1, 2, 5, 6].filter (item => Item% 2 = = 0);//=> [2, 6]

The arrow function brings a lighter syntax that does not include a detailed keyword function. When a function has only 1 statements, you can even omit the return.

An arrow function is anonymous, which means that the Name property is an empty string ". In this way, it has no lexical function name (which is useful for recursive, detach event handlers).

It also does not support arguments objects, unlike ordinary functions. Then he can support the remaining parameters after ES2015:

var sumarguments = (... args) => {  
   console.log (typeof arguments);//=> ' undefined ' return
   args.reduce ( result, item) => result + Item);
Sumargume
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.