let pages2 = {
home: {
title : "Home",
url: "index.html",
getAbsoluteURL: function (base) {
return `${base}/${this.url}`;
},
},
about: {
title : "About me",
url: "about.html",
getAbsoluteURL: function (base) {
return `${base}/${this.url}`;
},
},
contact: {
title : "Contact",
url: "contact.html",
getAbsoluteURL: function (base) {
return `${base}/${this.url}`;
}
},
};
We’ve seen objects whose values are [primitives](#primitives), other [objects](#objects), or [arrays](#arrays).
But they can also be [functions](#functions)!
These functions are called _methods_ because they typically have an implicit parameter: the object they are called on.
We can access that parameter with the special `this` keyword, as long as we’re using a regular function
(not an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) like in the previous slide).
Notice that the function here is identical for all three objects.
Can we reduce this repetition?
Classes
Blueprints for objects
Class definition
The blueprint
class Page {
constructor(title, url) {
this.title = title;
this.url = url;
}
getAbsoluteURL(base) {
return `${base}/${this.url}`;
}
}
Usage
“Creating instances”
let pages = {
home: new Page("Home", "index.html"),
about: new Page("About me", "about.html"),
contact: new Page("Contact", "contact.html"),
};
Classes are a way to create objects that share the same structure and behavior.
They are a way to create _blueprints_ for objects.
- The `constructor` method is called when a new object is created from the class.
- The `new` keyword is used to create a new object from a class.
- The `this` keyword is used to refer to the object that is being created.
- Any methods defined on the class (e.g. the `getAbsoluteURL()` method here) is shared by all objects created from the class (_instances_).
- Read more: [MDN: Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)