Let's now add some methods to our class. Here we will use the prototype
object to define them.
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();
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.
var Book = function(isbn, title) { this.isbn = isbn; this.title = title; }
In this code, we have our constructor like before:
Book.prototype = {
Then, we start the declaration of the prototype, ready to fill it in with our own method definitions:
printTitle: function(){ print("Title is " + this.title); },
Here, we put our first method as described with a function body:
printISBN: function() { print("ISBN is " + this.isbn); }
Then, our next method comes along. Here we end the definition without putting a comma.
var book = new Book("1234", "A good title");
After that, we declare a book
variable by constructing the Book
object with specified arguments.
book.printTitle(); book.printISBN();
Finally, we use our method by just calling it (note the brackets after the name of the method).