简体   繁体   中英

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

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM