Javascriptthis: some learning summary_javascript skills

Source: Internet
Author: User
I believe that anyone with C ++, C #, Java, and other programming experience will not be familiar with this keyword. Javascript is an object-oriented programming language. It contains the this keyword like C ++, C #, or Java. Next we will introduce the this keyword in Javascript. 1.1.1 Summary
I believe that anyone with C ++, C #, Java, and other programming experience will not be familiar with this keyword. Javascript is an object-oriented programming language. It contains the this keyword like C ++, C #, or Java. Next we will introduce this keyword in Javascript.
Contents
This in Global Code
This in the function
Reference Type
Function call and non-reference type
Reference Type and null value of this
This value when the function is called as the constructor
Manually set the value of this for function calls.

1.1.2 text

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

The Code is as follows:


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


This in Global Code

The Code is as follows:


// 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 explicitly and implicitly defined the global attributes foo1, foo2, and foo3. Since this is in a global context, so its value is the global object itself (window object in the browser); Next we will introduce this in the function.
This in the function
When this is used in function code, the situation is much more complicated and may cause many problems.
The first feature (and most important) of this value in Function Code is that it is not statically bound to a function.
As mentioned earlier, the value of this 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. It is impossible to assign a new value to this, because this is not a variable at all.
Next, we will illustrate this in the function through a specific example.
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:

The Code 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 code above, we found that when calling the "say ()" method of person, this points to the person object. When using the value assignment method, the "say ()" method of foo points to the "say ()" method in peson () method. We call the say () method of foo and find that this does not point to the person object, rather than the foo object. What is the reason?
First, we must know that the value of this is non-static in the function. Its value is determined before the specific code is executed when the function is called, the value of this is determined by the caller who activates the context Code. For example, the outer context of the called function. More importantly, the value of this is determined by the form of the called expression, therefore, this is not statically bound to a function.
Since this is not statically bound to a function, can we dynamically modify the value of this in the function?

The Code is as follows:


// 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 we dynamically modify the value of this in method say (). When we re-execute the above Code, we find that the value of this is wrong. This is because the value of this is determined once the code is executed (before the code is executed when the function is called), so it cannot be changed.
Reference Type
As mentioned above, the value of this is determined by the caller who activates the context code. More importantly, the value of this is determined by the form of the call expression; how does the expression form affect the value of 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:

The Code is as follows:


// 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 an unrestricted attribute of the variable name, function name, function parameter name, and global object.

The Code is as follows:


// Declares varible.
Var foo = 23;
// Declares a function
Function say (){
// Your code.
}


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

The Code is 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:

The Code is as follows:


// 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:

The Code is 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 its corresponding this attribute will also point to the foo object.
Assume that we call the say () method directly. Its reference type is as follows:

The Code is as follows:


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


Since the base attribute value of the say () method is global (usually window object), its corresponding this attribute will also point to global.
In the context of a function, the value of this 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 (), the value of this will be set as the base Object of the reference type value. In all other cases (non-reference type), the value of this is always null. However, since null is meaningless for this, 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, the value of this is 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:

The Code 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), the value of this is set as a global object.

The Code is as follows:


// 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, but the final value of this 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 means that the value of this will be set to null and 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, the value of this becomes a global object.
Reference Type and null value of this
For the situations mentioned above, there are exceptions. When the call expression has a reference type value on the left, but the value of this is null, it is eventually changed to 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. Use the following code to introduce the active object:

The Code is as follows:


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


Because the activation object always returns the value of this -- null (expressed by pseudo code AO. bar () is equivalent to null. bar (). Then, the value of this 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):
This value when the function is called as the constructor
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 is called, and the value of this in all Foo () functions is set as the newly created object.

The Code is as follows:


// 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 when the function is called.


The Function. prototype defines two methods, allowing you to manually specify the value of this when the Function is called. The two methods are:. apply () and. call (). Both methods accept the first parameter as the value of this in the call context. The difference between the two methods is that the passed parameter,. for the apply () method, the second parameter accepts the array type (or the object of the class array, such as arguments), and. the call () method accepts any number of parameters (separated by commas). Only the first parameter is required for the two methods -- the value of this.
The sample code describes how to use the call () and apply () methods:

The Code is as follows:


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 the required this value. Then we can pass any number of parameters and introduce the use of the apply () method.

The Code is as follows:


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 how to use this in Javascript. More importantly, it helps us better understand the change of this value in the global, function, constructor, and some special cases.

In the context of a function, the value of this 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 (), the value of this will be set as the base Object of the reference type value. In all other cases (non-reference type), the value of this is always null. However, since null is meaningless for this, it is implicitly converted to a global object.
For special cases, we need to remember the value assignment operator, comma operator, and | logical expression, which will cause this to lose the original reference type value and change it to the function type, the value of this 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/

[Author]: JK_Rush
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.