You could build a method in the Library class to achieve this. For example:
Define the Library object.
function Library (name) {
this.libraryName = name;
this.books = [];
}
Define a prototype method 'addBook'
Library.prototype.addBook = function(book) {
book.libraryName = this.libraryName;
this.books.push(book);
}
As you can see in the addBook method, the book is given the name of the library and added to the library's book array. Alternatively you could add a reference to the library object itself.
Alternative prototype method 'addBook'
Library.prototype.addBook = function(book) {
book.library = this;
this.books.push(book);
}
This ensures if the library name is updated later on, fetching it from the Book object will point directly to the library object and therefore stay up to date.
Next we define the Book object.
function Book (name) {
this.bookName = name;
this.library = {};
}
That's all we need. Now we can interface with these objects.
//First we declare the objects
var hp = new Book("Harry Potter"),
lib = new Library("Village Library");
//Add the book to the library
lib.addBook(hp);
//Outputs 'Village Library'
console.log(hp.library.libraryName);
lib.libraryName = "The new Library";
//Outputs 'The new Library'
console.log(hp.library.libraryName);
As an extra, if you wanted the ability for a book to be in multiple libraries, just change the Book object slightly like so:
function Book (name) {
this.bookName = name;
this.libraries = [];
}
You'll also have to modify the 'addBook' method.
Library.prototype.addBook = function(book) {
book.libraries.push(this);
this.books.push(book);
}
And that's it!