1

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

1
  • No questions are stupid, If you are unsure it Doesnt hurt to ask. Commented Jul 7, 2015 at 13:08

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You call bookmarks as a function yet in my example it's bookmarks = {}. Doing this.bookmarks.book would allow me to access it using this.book in the bookmarks init function, correct?
Correct. I thought bookmarks was a prototype too, but for anonymous objects it would work the same.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.