Reputation: 21
I do not understant, how to use Object.prototype pattern with classes (es6);
This is my code, I'm not sure, that I've used Object.prototype in the right way
class Course{
constructor(title, author) {
this.title = title;
this.author = author;
}
}
Course.prototype.toString = function (arguments) {
console.log(this.title + "... Author: " + this.author);
};
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();
}
Should I use something different?
Upvotes: 0
Views: 58
Reputation: 36630
In your following code:
class Course {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
Course.prototype.toString = function(arguments) {
console.log(this.title + "... Author: " + this.author);
};
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();
A class is nothing more than syntactic sugar which resembles the functionality of a constructor function. We can observe this more depth in the following example:
class Person {
}
console.log(typeof Person);
The class Person is actually a constructor function object. Just like normal constructors functions we can extend the prototype by putting properties on the prototype object.
So in your example:
Course.prototype.toString = function(arguments) {
console.log(this.title + "... Author: " + this.author);
};
What actually happens under the hood is that you are putting a property called toString on the Course
constructor function object.
Upvotes: 0
Reputation: 322
Writing an application using es6 classes is an alternative to developing using the prototype pattern directly.
Under the hood, es6 classes actually compile down to the prototype structure. But es6 classes tend to be easier to read, and when your application gets very large this can make all the difference.
In your case you would place the methods you want attached to the prototype inside the class you've created. This looks more similar to classic object oriented programming, as you would see in C++ or Java.
You can read more about es6 classes on MDN here
Per your example:
class Course {
constructor(title, author) {
this.title = title;
this.author = author;
}
toString(arguments) {
console.log(this.title + "... Author: " + this.author);
}
}
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();
Upvotes: 1
Reputation: 2011
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
ES6 classes is syntax sugar that allows you to avoid using Object.prototype, you simply define class methods like this:
class Course{
constructor(title, author) {
this.title = title;
this.author = author;
}
toString(arguments) {
console.log(this.title + "... Author: " + this.author);
}
}
Upvotes: 4