Javascript This is some learning summary _javascript tips

Source: Internet
Author: User
1.1.1 Summary
Believe that you have C + +, C # or Java programming experience, you are familiar with this keyword. Since JavaScript is an object-oriented programming language that contains the This keyword as C + +, C #, or Java, we'll introduce you to the This keyword in JavaScript.

This article directory

• This in global code
• This in the function
• Reference type
• function calls and non-reference types
• Reference type and null value of this
• Value of this function as constructor is invoked
• Manually set the value of this when the function is called

1.1.2 Body


Since many object-oriented programming languages contain the This keyword, we naturally associate this with object-oriented programming, this typically points to objects that are newly created with constructors. In ECMAScript, this is not only used to represent the created object, but also an attribute of the execution context:
Copy Code code as follows:

Activeexecutioncontext = {
Variable object.
VO: {...},
This:thisvalue
};

This in the global Code
Copy Code code as follows:

Global Scope
The implicit property of
The Global object
FOO1 = "ABC";
alert (FOO1); Abc

The explicit property of
The Global object
This.foo2 = "Def";
alert (FOO2); Def

The implicit property of
The Global object
var Foo3 = "Ijk";
alert (FOO3); Ijk

We have previously defined global properties foo1, Foo2, and Foo3 explicitly and implicitly, because this is in the global context, so its value is the global object itself (in the browser it is Window object), and then we'll introduce this in the function.

This in the function

When this is in the function code, the situation is much more complex and causes a lot of problems.

The first attribute of this value in the function code (and also the most important feature) is that it is not statically bound on the function.

As mentioned earlier, the value of this is determined at the stage of entering the execution context (excution contexts) and, in the case of the function code, the values are different each time.

However, once you enter the execution code phase, the value cannot be changed. It is not possible to assign a new value to this because at that time this is not a variable at all.

Next, we illustrate this in the function with a concrete example.

First we define two objects Foo and Person,foo contain a property name, while the person contains the attribute name and method say (), which are defined as follows:
Copy Code code 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 to
The same function say
Foo.say = Person.say;

Foo.say (); My name is Foo.

With the above code, we found that when invoking the Say () method of person, this points to the person object when the say () method of Foo is assigned to the Say () method in Peson. What is the reason that we call Foo's say () method and find that this is not pointing to the person object, not to the Foo object?

First, we must know that the value of this is non-static in the function, its value determines that, before a function call, the value of this is determined by the caller who activated the context code, for example, by invoking the outer layer of the function, and more importantly, the value of this is determined by the form of the invocation expression. So this is not a static binding on a function.

Since this is not statically bound to a function, can we dynamically modify the value of this in a function?
Copy Code code 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, in the method say (), we modify the value of this dynamically, and when we rerun the above code, we find that the value of this refers to an error. This is because once you enter the execution code phase (the function call, before the specific code executes), this value is determined, so it cannot be changed.

Reference type

We mentioned earlier that the value of this is determined by the caller who activated the context code, and more importantly, the value of this is determined by the form of the invocation expression, so how does the form of the expression affect the value of this?

First, let's introduce an internal type--a reference type whose value can be represented in pseudocode as an object that has two properties: the base property (the object to which the property belongs) and the PropertyName property in the Base object:
Copy Code code as follows:

Reference type.
var Valueofreferencetype = {
Base:mybase,
PropertyName: ' Mybasepropertyname '
};

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

• When dealing with an identifier
• Or when a property is accessed
Identifiers are actually variable names, function names, function parameter names, and the unrestricted properties of global objects.

Copy Code code as follows:

Declares Varible.
var foo = 23;

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

In the middle process, the corresponding reference types are as follows:
Copy Code code as follows:

Reference type.
var fooreference = {
Base:global,
PropertyName: ' foo '
};

var sayreference = {
Base:global,
PropertyName: ' Say '
};

We know there are two ways to attribute access in javascript: dot notation and bracket notation:
Copy Code code as follows:

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

Because the Say () method is an identifier, it corresponds to the Foo object reference type as follows:
Copy Code code as follows:

Reference type.
var foosayreference = {
Base:foo,
PropertyName: ' Say '
};

We found that the base property value of the Say () method is the Foo object, and its corresponding this property also points to the Foo object.

Suppose we call the Say () method directly, and it corresponds to the following reference type:
Copy Code code as follows:

Reference type.
var sayreference = {
Base:global,
PropertyName: ' Say '
};

Because the base property value of the Say () method is global (usually window object), its corresponding this property also points to global.

The value of this in a function context is provided by the function caller and is determined by the form of the current invocation expression. If the value of the reference type is on the left side of the call bracket (), then the value of this is set to the base object for the reference type value. All other cases (unreferenced types), the value of this is always null. However, because null has no meaning for this, it is implicitly converted to a global object.

function calls and non-reference types
As we mentioned earlier, when the left side of the call bracket is a unreferenced type, the value of this is set to null and eventually implicitly converted to the global object.

Now we have defined an anonymous self execution function, which is implemented as follows:
Copy Code code as follows:

Declares anonymous function
(function () {
alert (this); Null => Global
})();

Because the anonymous function to the left of parentheses () is a unreferenced type object (it is neither an identifier nor a property access), the value of this is set to the global object.
Copy Code code 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

Notice here that in four expressions, only the first expression this is pointing to the Foo object, while the other three expressions perform global.

Now we have a question: why attribute access, but the value of the final this is not a reference type object but a global object?

We notice that expression two is an assignment (assignment operator), unlike an expression set of operators, which triggers the invocation of the GetValue method (see step three in 11.13.1). The final return is a function object (not the value of the reference type), which means that the value of this is set to null and eventually becomes a global object.

The third and fourth cases are similar--both the comma operator and the or logical expression trigger the call to the GetValue method, and the corresponding loss of the original reference type value becomes the function type, and the value of this becomes the global object.

reference type and null value of this
For the case mentioned earlier, there are exceptions, when the value of the reference type is to the left of the invocation expression, but the value of this is null and eventually becomes the global object. This condition occurs when the base object that refers to the type value is exactly the active object (Activation object).

This happens when an internal child function is called in the parent function, and the active object is described by the following schematic code:
Copy Code code as follows:

declares Foo function.
function foo () {
function Bar () {
alert (this); Global
}
The same as Ao.bar ().
Bar ();
}

Because the active object (activation object) always returns the This value to--null (Ao.bar () is the equivalent of Null.bar () in pseudocode), then the value of this will eventually be converted from null to the global object.

An exception occurs when a function call is contained in a code block of a with statement, and the With object contains a function property. The With statement adds the object to the front of the scope chain, before the active object. Correspondingly, in the case of a reference type's value (identifier or property access), the base object is no longer an active object, but an object of the WITH statement. Also, 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:

value of this when a function is invoked as a constructor
function as a constructor, we create an instance object from the new operator, it calls the internal [[construct]] method of the Foo () function, and after the object is created, the internal [call] method is invoked, and then all foo () The value of this in the function is set to the newly created object.
Copy Code code 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

to manually set this value when a function is called
The Function.prototype prototype defines two methods that allow 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 argument as the value of this in the calling context, and the difference between the two methods is the parameter passed, and for the. Apply () method, the second parameter accepts the array type (or the object of the class array, such as arguments), and. Call () Method accepts any number of arguments (separated by commas); These two methods have only the first parameter is the necessary--this value.

Describes the use of the call () method and the Apply () method using the sample code:
Copy Code code as follows:

var myObject = {};
var myfunction = function (param1, param2) {
Setviacall () ' This ' points to my Object when the 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 necessary this value, and then we can pass any number of arguments and then introduce the use of the Apply () method.
Copy Code code as follows:

var myObject = {};
var myfunction = function (param1, param2) {

Set via Apply (), this points to me 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);

By comparing the call () method, we find 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 describes the use of this in JavaScript and, more importantly, helps us better understand the value changes in the global, function, constructor, and some special cases.

The value for this in the function context is provided by the function caller and is determined by the form of the current invocation expression. If the value of the reference type is on the left side of the call bracket (), then the value of this is set to the base object for the reference type value. All other cases (unreferenced types), the value of this is always null. However, because null has no meaning for this, it is implicitly converted to a global object.

For exceptional cases, we want to remember the assignment, the comma operator, and the | | Logical expression, which causes this to lose the original reference type value and becomes the function type, the value of this becomes the global object.

Reference
[1] http://dmitrysoshnikov.com/ecmascript/chapter-3-this/English version
[2] http://blog.goddyzhao.me/post/11218727474/this translation
[3] https://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/
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.