this in Class Bodies

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

Within the constructor of a class, this refers to the newly created object. Within a method, however, this might refer to another value if the method is called as an ordinary function. Just like any other object method, class methods can lose their intended receiver this way.

This lesson shows different approaches to solving this problem either by binding class methods or by using class fields with arrow functions instead.

Instructor: [00:00] Here we have a short Person class that defines a constructor and the sayHi() method we've seen before. Now let's create an instance of that class and call the sayHi() method. As you can see, everything works fine.

[00:21] Within the constructor, "this" refers to the newly created instance of that class. When we call person.sayHi(), we invoke sayHi() as as method with person as a receiver. Therefore, the "this" binding is correct. If we store a reference to the sayHi() method, though, and later invoke it as a function, we once again lose the receiver of the method.

[00:47] The "this" argument within sayHi() is now set to undefined. This is because class bodies are implicitly in strict mode. We're invoking greet as an ordinary function. We've seen that no autobinding is happening, but we could manually call bind() to tie this sayHi() function to Person.

[01:11] A variation of this approach is to bind the sayHi() method within the constructor of the class. Another possibility would be to use a class field and an arrow function. Class fields are modern ECMAScript syntax, and they look like this. Now we no longer need to call bind() because "this" within the arrow function already refers to the instance of the class.

[01:50] My Node version doesn't support class fields yet, so I'm first going to compile my code using Babel. As you can see, the class field has been transformed into a property assignment in the constructor. I can now pipe that code into Node. Everything works as intended.

Vamshi
Vamshi
~ 6 years ago

Freakin awesome!

Matthias Hryniszak
Matthias Hryniszak
~ 6 years ago

Very nice explanation.

Gisele
Gisele
~ 6 years ago

Hi, what is this babel | node? It's from node?

Marius Schulz
Marius Schulzinstructor
~ 6 years ago

@Gisele: I'm using a Unix Pipeline to feed the output generated by npm run babel directly into node to execute the transpiled JavaScript code.

Gisele
Gisele
~ 6 years ago

So it's some kind of comand-line? Like prompt (windows) or git bash?

Marius Schulz
Marius Schulzinstructor
~ 6 years ago

@Gisele: | is shell syntax that can be used on the command line, yes.

Erin Eland
Erin Eland
~ 5 years ago

@Marius, great course, love how specific and concise this is! (pun intended)

Markdown supported.
Become a member to join the discussionEnroll Today