"this" and Regular Functions

To get a handle on how thisworks differently with arrow functions, let's do a quick recap of how thisworks in a standard function. If you have a solid grasp of how thisworks already, feel free to jump over this section.

The value of thethiskeyword is based completely on how its function (or method) is called.thiscould 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 ofthisinside theSundaeconstructor 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 ofthisinsideprintName()will refer toobj2since the first parameter ofcall()is to explicitly set whatthisrefers 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 ofthisinsideteleport()will refer todata.


4. The global object or undefined

If the function is called with no context:

teleport();

In the code above, the value ofthisinsideteleport()is either the global object or, if in strict mode, it'sundefined.


TIP: thisin JavaScript is a complicated topic. We just did a quick overview, but for an in-depth look at how thisis 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 ofthisinside theTrainconstructor function below?

const redTrain = new Train('red');
  • the window object

  • a 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 thisinside the increaseSpeed()function below?

const redTrain = new Train('red');
redTrain.increaseSpeed(25);
  • the window object

  • a new object

  • the 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.

results matching ""

    No results matching ""