Classes

ES2015 introduces classes, which is primarily a syntactical sugar over prototype-based inheritance. With the class syntax, you can create constructors, extends from a superclass, and create static methods, as well as getters and setters.

Let's see the following example that uses the class syntax to implement User, and TeamMember:

1.  class User {
2. constructor(name, interests) {
3. this.name = name;
4. this.interests = interests;
5. }
6. greeting () {
7. console.log('Hi, I'm ' + this.name + '.');
8. }
9. get interestsCount () {
10. return this.interests ? this.interests.length : 0;
11. }
12. }

In lines 1 to 12, we define class Userwhich accepts two arguments via its constructor. It has a greeting() method and an interestsCount getter:

13. class TeamMember extends User {
14. constructor(name, interests) {
15. super(name, interests);
16. this._tasks = [];
17. this._welcomeText = 'Welcome to the team!';
18. }
19. greeting () {
20. console.log('I' m ' + this.name + '. ' + this._welcomeText);
21. }
22. work () {
23. console.log('I' m working on ' + this._tasks.length + '
tasks.')
24. }
25. set tasks (tasks) {
26. let acceptedTasks = [];
27. if (tasks.length > TeamMember.maxTasksCapacity()) {
28. acceptedTasks = tasks.slice(0,
TeamMember.maxTasksCapacity());
29. console.log('It's over max capacity. Can only take two.');
30. } else {
31. acceptedTasks = tasks;
32. }
33. this._tasks = this._tasks.concat(acceptedTasks);
34. }
35. static maxTasksCapacity () {
36. return 2;
37. }
38. }

In lines 13 to 38, we create a TeamMember class to extend from User. In its constructor, it calls the constructor of the User with super to instantiate the properties of name and interests. We also define two additional properties, _tasks and _welcomeText. The preceding underscore suggests that they are regarded as private properties and should not be changed directly from outside. However, nothing is private in JavaScript. You can still access these properties, for example, member._tasks, and member._welcomeText.

We override the greeting() method of user in line 20 and add a new work() method in line 22. In lines 25 to 34, we define a setter tasks, inside which we access the maxTasksCapacity() static method of TeamMember:

39. let member = new TeamMember('Sunny', ['Traveling']);
40. member.greeting(); // I' m Sunny. Welcome to the team!
41. member.tasks = ['Buy three tickets', 'Book a hotel', 'Rent a car'];
// It's over max capacity. Can only take two.
42. member.work(); // I' m working on 2 tasks.
43. console.log(member.interestsCount); // 1
44. member.interestsCount = 2; // This won’t save the change
45. console.log(member.interestsCount); // 1
46. console.log(member.tasks); // undefined

As you can see, in lines 39 to 43, the member object has all the features of the User class and TeamMember, working as expected. In lines 44 to 45, we try to make changes to member.interestsCount, but it won't work because there is no setter defined. And line 46 shows that accessing member.tasks results in undefined because we didn't define a getter for it.

You cannot use member.constructor to access the constructor of the TeamMember defined in line 14. It is for accessing the member object’s constructor function, in this case, TeamMember.

And now let's see how to add a new method, eat(), to the User class:

User.prototype.eat = function () {
console.log('What will I have for lunch?');
};
member.eat(); // What will I have for lunch?

You still need to add it to the prototype object of User. If you add it directly to User as follows, you will get TypeError:

User.sleep = function () {
console.log('Go to sleep');
};
member.sleep(); // Uncaught TypeError: member.sleep is not a function
User.sleep(); // Go to sleep

It is because as a result of writing in this way that you add sleep as a property of the User class itself or, more precisely, the User constructor function itself. And you might have already noticed that sleep becomes a static method of the User class. When using the class syntax, when you define a method, behind the scene, JavaScript adds it to its prototype object, and when you define a static method, JavaScript adds it to the constructor function:

console.log(User.prototype.hasOwnProperty('eat'));  // true
console.log(User.hasOwnProperty('sleep')); // true
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.83.176