Time for action – adding prototypes

Let's now add some methods to our class. Here we will use the prototype object to define them.

  1. Create a new script called hello-world-prototype.js and fill it with this:
    #!/usr/bin/env seed
    
    print("Hello world")
    
    var Book = function(isbn, title) {
       this.isbn = isbn;
       this.title = title;
    }
    
    Book.prototype = {
       printTitle: function(){
          print("Title is " + this.title);
       },
    
       printISBN: function() {
          print("ISBN is " + this.isbn);
       }
    }
    
    var book = new Book("1234", "A good title");
    book.printTitle();
    book.printISBN();
  2. Run it.
  3. See the values printed:
    Hello world
    Title is A good title
    ISBN is 1234
    

In a JavaScript object, prototype is a special object that holds all the properties and methods inside a class or an object. So what we do here is to fill in the prototype with our own methods.

In this code, we have our constructor like before:

Then, we start the declaration of the prototype, ready to fill it in with our own method definitions:

Here, we put our first method as described with a function body:

Then, our next method comes along. Here we end the definition without putting a comma.

After that, we declare a book variable by constructing the Book object with specified arguments.

Finally, we use our method by just calling it (note the brackets after the name of the method).

Why don't we add more methods? Let's say we need these methods: