Is it possible to use arrow functions to define a method inside a class?
If it's possible. How can I define the method bark() in the bellow example with arrow function?
class Dog {
constructor(name, bread) {
this.name = name;
this.bread = bread;
}
bark() {
return `Bark Bark! My name is ${this.name}`;
}
}
const mini = new Dog('Mini', 'Spitz');
mini.bark();
I tried this, but it's saying: Uncaught SnytaxError.
bark = () => {
return `Bark Bark! My name is ${this.name}`;
}
Top comments (5)
It is possible but I don't know what you would gain by doing it.
In the constructor, I am making a variable, which can be called on an instance thanks to the
this
keyword, and I'm assigning a function to it.May I ask why you're asking? 🙂
Thanks.
I see that in your example the bark() method is added to the object itself but not to its prototype.
Would it be possible to add the bark() method to the Dog.prototype using the class syntax?
But actually the background of my question is that I'm learning React and write now I'm a bit confused.
As we know, we shouldn't use arrow functions to define an object method.
This one works:
But this one doesn't work:
So far so good. But what about ES6 Classes? Is the above statement also true for ES6 Classes?
An arrow function is, basically, a replacement for the
function
keyword. There is a bit more nuance to it but that's the basic rule.If you weren't using
function
before you don't need to use it now.The primary use of an arrow function is to bind the context so that "this" becomes lexical and not determined at run time. This is super helpful when writing React!
Though I will admit that arrow functions are quite snazzy looking and using it just because it looks better is totally valid.
This is possible and a common pattern in React. But it's currently not part of the ECMAScript standard so it will be a while before it's natively implemented. If you're using Babel, look at this plugin.
Here's the proposal for this to happen, it's currently in Stage 3, which means it's a good candidate to be accepted and likely to be implemented.