styke
styke

Reputation: 2174

How to access the prototype object from another object within it

My knowledge of prototypes is still in its infancy, so please bear with me. I have a main object that is initialised via var book = new book();

I initiate some prototype functions:

book = function(){
    this.init();
}

book.prototype.init = function() {
    //etc.
}

And I also initialise an object:

book.prototype.bookmarks = {
    init : function(){
        //How can I access book from this function?
    }
}

I mean I could use book.someFunction() but I'm just curious if there's a way to properly access the top level object. Sorry if this is a stupid question, I'll try and clarify anything unclear. Thanks

Upvotes: 1

Views: 54

Answers (2)

rgbchris
rgbchris

Reputation: 816

I'm likely making some assumptions here, but this might be along the lines of what you are looking for in terms of accessing the instantiated book.

function Book(title) {
    this.title = title;
    this.init();
}

Book.prototype = {
    title: null,
    page:  null,
    init: function() {
        // Initialize book
    },
    bookmark: function(page) {
        if (page) {
            this.page = page;
        } else {
            return this.page || 'No Bookmark';
        }
    }
}

var myBook = new Book('The Catcher in the Rye');
myBook.bookmark('pg 36');
myBook.bookmark(); // => pg 36

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116200

No, not automatically. That is, you have to tell the subobject what the top object is, so in the init function of book, you'd get something like this:

init = function() {
    // Create the bookmarks instance and assign it to the property of book.
    this.bookmarks = new bookmarks();
    // Tell the bookmarks about me, the book object.
    this.bookmarks.book = this;
}

Upvotes: 3

Related Questions