Categories
JavaScript Object-Oriented Design Programming

JavaScript Class and Method

To myself… Even if you hate how JavaScript classes are designed, you must know the class context by heart to avoid encountering type error exceptions in your code.

Creating an object

Suppose we need a JavaScript program to log any dog name to the browser console. We can start off by creating a blueprint of a Dog using class keyword in ES6 like this:

class Dog {
  printName(name) {
    this.print(`My name is ${name}`)
  }

  print(text) {
    console.log(text)
  }
}

const myDog = Dog()
myDog.printName('Tyler') // error here

What’s interesting in this piece of code is that the printName context changes and expectations are thrown.

Uncaught TypeError: Cannot read property 'print' of undefined

This is because the methods inside a class are bound to the class prototype and NOT to the class instance.

Binding a method to the class instance

So what we can do to make our code work?

One way is to bind the method to the class instance explicitly using bind keyword in the constructor by hand.

class Dog {
  constructor () {
    this.printName.bind(this)
  }
}

There are other ways to attach the method to the object instance but for now, we’ll stick to this since it’s the easiest and straight forward solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s