Introduction
In this article, we will discuss more details directly related to the execution context. The topic of the discussion is the this keyword.
Practice has shown that this topic is difficult, and the determination of this value in different execution contexts often leads to problems.
Many programmers tend to think that in programming languages, this keyword is closely related to object-oriented programs and completely points to new objects created through constructors. This is also done in ECMAScript, but as you can see, this is not limited to the definition of creating objects.
Let's take a closer look at the true this value in ECMAScript?
Definition
This value is an attribute in the execution context.
activeExecutionContext = { VO: {...}, this: thisValue};
VO makes the variable object we discussed earlier.
This is closely related to the executable code in the context. this value depends on the context in which the code runs.
This value in Global Code
Everything is simple here. In global code, this is always a global object, which may be referenced indirectly.
// explicit property definition of// the global objectthis.a = 10; // global.a = 10alert(a); // 10// implicit definition via assigning// to unqualified identifierb = 20;alert(this.b); // 20// also implicit via variable declaration// because variable object of the global context// is the global object itselfvar c = 30;alert(this.c); // 30
This value in Function Code
It is interesting to use this in function code, which is difficult and can cause many problems.
In this type of code, the primary feature (or perhaps the most important) of this value is that it is not statically bound to a function.
As we have mentioned above, this value depends on the context of the entry. In a function code, this value is completely different each time.
However, the this value remains unchanged during code execution. That is to say, since it is not a variable, it is impossible to assign a new value to it (on the contrary, in the Python programming language, it is clearly defined as the object itself and can be changed continuously during runtime ).
var foo = {x: 10};var bar = { x: 20, test: function () { alert(this === bar); // true alert(this.x); // 20 this = foo; // error alert(this.x); // if there wasn't an error then 20, not 10 }};// on entering the context this value is// determined as "bar" object; why so - will// be discussed below in detailbar.test(); // true, 20foo.test = bar.test;// however here this value will now refer// to "foo" – even though we're calling the same functionfoo.test(); // false, 10
- 5 pages in total:
- Previous Page
- 1
- 2
- 3
- 4
- 5
- Next Page