"this" and Regular Functions
To get a handle on how this
works differently with arrow functions, let's do a quick recap of how this
works in a standard function. If you have a solid grasp of how this
works already, feel free to jump over this section.
The value of thethis
keyword is based completely on how its function (or method) is called.this
could be any of the following:
1. A new object
If the function is called withnew
:
const mySundae = new Sundae('Chocolate', ['Sprinkles', 'Hot Fudge']);
In the code above, the value ofthis
inside theSundae
constructor function is a new object because it was called withnew
.
2. A specified object
If the function is invoked withcall
/apply
:
const result = obj1.printName.call(obj2);
In the code above, the value ofthis
insideprintName()
will refer toobj2
since the first parameter ofcall()
is to explicitly set whatthis
refers to. 위의 코드에서 printName () 내부의 "this"값은 obj2를 참조합니다. call ()의 첫 번째 매개 변수는 "this"가 참조하는 것을 명시 적으로 설정하기 때문입니다.
3. A context object
If the function is a method of an object:
data.teleport();
In the code above, the value ofthis
insideteleport()
will refer todata
.
4. The global object or undefined
If the function is called with no context:
teleport();
In the code above, the value ofthis
insideteleport()
is either the global object or, if in strict mode, it'sundefined
.
TIP:
this
in JavaScript is a complicated topic. We just did a quick overview, but for an in-depth look at howthis
is determined, check out this All Makes Sense Now!from Kyle Simpson's book series You Don't Know JS.
QUESTION 1 OF 2
What is the value ofthis
inside theTrain
constructor function below?
const redTrain = new Train('red');
the window objecta new object
undefined
SUBMIT: Since the new
keyword was used, the correct answer is a new object.
QUESTION 2 OF 2
What is the value of this
inside the increaseSpeed()
function below?
const redTrain = new Train('red');
redTrain.increaseSpeed(25);
the window objecta new objectthe redTrain object
undefined
SUBMIT: Since the increaseSpeed()
function is called from a context object ( redTrain
) that context object will be the value of this
in the function.