Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    this in Class Bodies

    Marius SchulzMarius Schulz

    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.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss