In this chapter, we will explore the following topics:
Programmers who use JavaScript can use classes to encapsulate units of logic in the same way as programmers of other languages. However, unlike those languages, JavaScript relies on a less popular form of inheritance known as prototype-based inheritance. Since Backbone classes are, at their core, just JavaScript classes, they too rely on the prototype system and can be subclassed in the same way as any other JavaScript class.
For instance, let's say you wanted to create your own Book
subclass of the Backbone Model
class with additional logic that Model doesn't have, such as book-related properties and methods. Here's how you can create such a class using only JavaScript's native object-oriented capabilities:
// Define Book's Initializer var Book = function() { // define Book's default properties this.currentPage = 1; this.totalPages = 1; } // Define book's parent class Book.prototype = new Backbone.Model(); // Define a method of Book Book.prototype.turnPage = function() { this.currentPage += 1; return this.currentPage; }
If you've never worked with prototypes in JavaScript, the preceding code may look a little intimidating. Fortunately, Backbone provides a much easier and easier to read mechanism for creating subclasses. However, since that system is built on top of JavaScript's native system, it's important to first understand how the native system works. This understanding will be helpful later when you want to do more complex class-related tasks, such as calling a method defined on a parent class.
3.22.61.226