Introduction
In this post, we will go over “this”. this explains the context when the code is carried out and can represent many things.
Execution Context
- When you write code and call it to the javascript engine, the engine creates the memory and execution context into objects.
-
In order to execute, various information is required and the execution context is managed as an object to classify information.
-
When a function is called, the information below is created as the execution context by the scope and pushed to the call stack. When the function is complete, it is popped from the call stack.
-
Variables in Scope : Local Variable, Parameter, Global Variable, Object Properties
-
Caller
-
Arguments
-
this
-
Therefore, when you declare a function with variables, local and local execution context are created. Javascript works with lexical scope, so where somethig is declared is important.
this
this keyword is a special distinguisher that is set automatically in all the scopes of functions. It is used as one of the factors that make up the execution context.
“this” is decided differently in each case, and there are five cases.
Global
-
Global: window
-
Function Call: window
When you make a variable in global scope and call the function, the variable is saved is a global scope “window”. Then, “this” for global and the function scope refers to window.
1 |
|
Parent Object
- Call Method: Parent object
As seen in two previous cases, this refers to the window in a normal function call. However, it changes when it is a method in an object.
1 |
|
“this” in a method of an object refers to the parent object. this.basic therefore means price.basic.
New Instance / Object
- Construction mode(“this” of an object created using the keyword new): New instance/ object
this is simple when used for OOP.
1 |
|
this refers to the newly created object in the case of OOP.
Binding Target: object on the left of the CALL TIME dot
What’s it for?: So methods run in the context of an object they’re found on.
.call / .apply
- The object put in as the first paremeter for .call or .apply (first argument)
1 |
|
me goes in as the parameter of call and is used when the function identify is called. “this” refers to me in this case.
1 |
|
“this” works in the same way for apply.
The different between call and apply is that call receives one parameter while apply receives the paramter as an array.
Conclusion
Check all five cases to see which context or what “this” refers to.