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:
const person = {
points: 23,
score() {
return this.points++; // this keyword refers to person object
}
};
person.score();
But this one doesn't work:
const person = {
points: 23,
score: () => { // using arrow function to define score method
return this.points++; // this keyword refers to window object
}
};
person.score();
So far so good. But what about ES6 Classes? Is the above statement also true for ES6 Classes?
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.