Summary of Javascriptthis-

Source: Internet
Author: User
1.1.1 I believe that anyone with experience in programming such as CC ++, C #, and Java will be familiar with this keyword. Javascript is an object-oriented programming language. It contains the this keyword like CC ++, C #, or Java, next we will introduce this... in Javascript ...,. 1.1.1 Summary

I believe that anyone with C/C ++, C #, Java, and other programming experienceThisThe keyword is no longer familiar. Because Javascript is an object-oriented programming language, it is similar to C/C ++, C #, or Java.ThisKeyword. Next we will introduce youThisKeyword.
1.1.2 text

Because many Object-Oriented Programming Languages containThisKeyword, we will naturally putThisAssociated with object-oriented programming methods,ThisIt usually points to the newly created object using the constructor. In ECMAScript,ThisIt is not only used to represent the created object, but also an attribute of the execution context:

ActiveExecutionContext = {
// Variable object.
VO :{...},
This: thisValue
};

In the global codeThis

// Global scope
// The implicit property
// The global object
Foo1 = "abc ";
Alert (foo1); // abc

// The explicit property
// The global object
This. foo2 = "def ";
Alert (foo2); // def

// The implicit property
// The global object
Var foo3 = "ijk ";
Alert (foo3); // ijk

Previously, we defined the global attributes foo1, foo2, and foo3 through explicit and implicit definitions.ThisIn the global context, the value of this parameter is the Global object (window object in the browser). Next we will introduceThis.
FunctionThis

WhenThisIn function code, the situation is much more complicated and causes many problems.
Function CodeThisThe first feature of the value (and also the most important feature) is:It is not statically bound to a function..
As mentioned earlier,ThisThe value of is determined at the stage of the execution context (Excution context), and in the function code, its values are different each time.
However, once the code is executed, its value cannot be changed. If you wantThisIt is impossible to assign a new value because at that timeThisIt is not a variable at all.
Next, we will illustrateThis.
First, we define two objects: foo and person. foo contains an attribute name, while person contains the attribute name and method say (). The specific definition is as follows:

// Defines foo object.
Var foo = {
Name: "Foo"
};

// Defines person object.
Var person = {
Name: "JK_Rush ",
Say: function (){
Alert (this = person );
Alert ("My name is" + this. name );
}
};

Person. say (); // My name is JK_Rush

// Foo and person object refer
// The same function say
Foo. say = person. say;

Foo. say (); // My name is Foo.

Through the above Code, we found that when we call the person's say () method, ThisPoint to the person object. When the foo's say () method points to the say () method in peson by assigning values. We call the say () method of foo and find that ThisIt does not point to the person object, but to the foo object. Why?
First, we must know ThisThe value of is non-static in the function. Its value is determined before the specific code is executed during the function call, ThisThe value is determined by the caller who activates the context Code. For example, the outer context of the called function. More importantly, This The value is determined by the form of the call expression.So This It is not statically bound to a function..
Because ThisIt is not statically bound to a function, so can we dynamically modify it in the function? This?

// Defines foo object.
Var foo = {
Name: "Foo"
};

// Defines person object.
Var person = {
Name: "JK_Rush ",
Say: function (){
Alert (this = person );
This = foo; // ReferenceError
Alert ("My name is" + this. name );
}
};

Person. say (); // My name is JK_Rush

Now, in the method say (), dynamically modifyThisWhen we re-execute the above Code, we find thatThisValue reference error. This is because, once the code is executed (before the specific code is executed when the function is called ),ThisAnd cannot be changed.
Reference Type

As mentioned aboveThisThe value is determined by the caller who activates the context code. More importantly,ThisThe value is determined by the form of the call expression. How is the form of the expression affected?This?
First, let's introduce an internal type-reference type. Its value can be expressed as a pseudo-code object with two attributes: base attribute (the object to which the attribute belongs) and the propertyName attribute in the base object:

// Reference type.
Var valueOfReferenceType = {
Base: mybase,
PropertyName: 'mybasepropertyname'
};

The value of the reference type can only be in the following two cases:

  • When processing an identifier
  • Or when accessing the attributes
The identifier is actually Variable name, Function Name, Function parameter nameAnd Unrestricted attributes of Global Objects.

// Declares varible.
Var foo = 23;

// Declares a function
Function say (){
// Your code.
}

During the intermediate process, the corresponding reference types are as follows:

// Reference type.
Var fooReference = {
Base: global,
PropertyName: 'foo'
};

Var sayReference = {
Base: global,
PropertyName: 'say'
};

We know that there are two methods to access property in Javascript: The dot symbol and the brackets symbol:

// Invokes the say method.
Foo. say ();
Foo ['say'] ();

Because the say () method is an identifier, it corresponds to the reference type of the foo object as follows:

// Reference type.
Var fooSayReference = {
Base: foo,
PropertyName: 'say'
};

We found that the base attribute value of the say () method is the foo object, so it corresponds ThisThe property also points to the foo object.
Assume that we call the say () method directly. Its reference type is as follows:

// Reference type.
Var sayReference = {
Base: global,
PropertyName: 'say'
};

Because the base attribute value of the say () method is global (usually window object ),ThisThe property will also point to global.
Function ContextThisThe value is provided by the function caller and determined by the form of the current call expression. If brackets () are called ()There is a reference type value on the left of, thenThisWill be set to the base of the reference type valueObject.In all other cases (non-reference type ),ThisThe value is always null.. However, since nullForThisTherefore, it is implicitly converted to a global object.
Function call and non-reference type

As mentioned above, when the left side of the call bracket is not of the reference type,ThisIs set to null, and is implicitly converted to a global object.
Now we have defined an anonymous self-execution function. The specific implementation is as follows:

// Declares anonymous function
(Function (){
Alert (this); // null => global
})();

Because the anonymous function on the left of the brackets () is a non-reference type object (it is neither an identifier nor an attribute access, ThisIs set as a global object.

// Declares object.
Var foo = {
Bar: function (){
Alert (this );
}
};

(Foo. bar) (); // foo.
(Foo. bar = foo. bar) (); // global?
(False | foo. bar) (); // global?
(Foo. bar, foo. bar) (); // global

Note that among the four expressions, only the first expression "this" points to the foo object, while the other three expressions execute global.
Now we have another question: Why is attribute access?ThisThe value of is not a reference type object but a global object?
We noticed that expression 2 is assignment operator. Unlike expression operators, it triggers the call to the GetValue method (see step 3 in 11.13.1 ). The final returned result is a function object (instead of a reference type value), which meansThisWill be set to null, and will eventually become a global object.
The third and fourth cases are similar-both the comma operator and the OR logical expression will trigger the call to the GetValue method, so the original reference type value will be lost and changed to the function type accordingly,ThisThe value is changed to a global object.
Reference Type andThisNull Value

For the situations mentioned above, there are exceptions. When the call expression has a reference type value on the left sideThisThe value is null and eventually becomes a global object ). In this case, the condition is that when the base object of the reference type value happens to be an active object (activation object ).
This happens when the internal sub-function is called in the parent function.The following sample code describes the active objects:

// Declares foo function.
Function foo (){
Function bar (){
Alert (this); // global
}
// The same as AO. bar ().
Bar ();
}

Because the activation object always returnsThisThe value is -- null (which is expressed by pseudo code AO. bar (), which is equivalent to null. bar (). Then,ThisThe value of is eventually changed from null to a global object.
When a function call is included in the with statement code block and the with object contains a function attribute, exceptions may occur. The with statement adds the object to the beginning of the scope chain before the active object. Correspondingly, when a value of the reference type (identifier or attribute access) is used, the base object is no longer an active object, but an object of the with statement. In addition, it is worth mentioning that it is not only for internal functions, but also for global functions, because the with object masks higher-level objects (global objects or active objects) in the scope chain):
When a function is called as a constructorThisValue

When a function is used as a constructor, we use the new operator to create an instance object, which calls the [[Construct] method inside the Foo () function. After the object is created, the internal [[Call] method will be called, and then all the Foo () functions willThisThe value is set as the newly created object.

// Declares constructor
Function Foo (){
// The new object.
Alert (this );
This. x = 10;
}

Var foo = new Foo ();
Foo. x = 23;
Alert (foo. x); // 23

Manually set the value of this for function calls.

Two methods are defined on the Function. prototype, allowing you to manually specify the Function call time.This. The two methods are:. apply () and. call (). Both methods accept the first parameter as the call context.ThisThe difference between the two methods is the passed parameter. For the. apply () method,The second parameter accepts the array type.(Or an object of the class array, such as arguments), and The. call () methodAccept any number of parameters(Separated by commas); these two methods are only required for the first parameter --This.
The sample code describes how to use the call () and apply () methods:

Var myObject = {};

Var myFunction = function (param1, param2 ){

// Setviacall () 'eas' points to my Object when function is invoked
This. foo = param1;
This. bar = param2;

// Logs Object {foo = 'foo', bar = 'bar '}
Console. log (this );
};

// Invokes function, set this value to myObject
MyFunction. call (myObject, 'foo', 'bar ');

// Logs Object {foo = 'foo', bar = 'bar '}
Console. log (myObject );

The first parameter of the call () method is required. ThisValue, then we can pass any number of parameters, and then introduce the use of the apply () method.

Var myObject = {};

Var myFunction = function (param1, param2 ){

// Set via apply (), this points to my Object when function is invoked
This. foo = param1;
This. bar = param2;

// Logs Object {foo = 'foo', bar = 'bar '}
Console. log (this );
};

// Invoke function, set this value
MyFunction. apply (myObject, ['foo', 'bar']);

// Logs Object {foo = 'foo', bar = 'bar '}
Console. log (myObject );

Compared with the call () method, we found that the apply () method and the call () method are not much different, except that the method signature is different.
1.1.3 Summary

This article introduces JavascriptThisMore importantly, it helps us better understandThisValue changes in global, function, constructor, and some special cases.
For function ContextThisThe value is provided by the function caller and determined by the form of the current call expression. If there is a reference type value on the left of the call bracket (),ThisWill be set to the base Object of the reference type value. In all other cases (non-reference type ),ThisIs always null. However, since null isThisTherefore, it is implicitly converted to a global object.
For special cases, we need to remember the value assignment operator, comma operator, and | logical expression to makeThisThe original reference type value is lost and changed to the function type,ThisThe value becomes a global object.
Reference

Http://dmitrysoshnikov.com/ecmascript/chapter-3-this/ English version
[2] http://blog.goddyzhao.me/post/11218727474/this
[3] https://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/

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.