簡體   English   中英

如何從其中的另一個對象訪問原型對象

[英]How to access the prototype object from another object within it

我對原型的了解還處於起步階段,所以請耐心等待。 我有一個主要對象,通過var book = new book()初始化;

我啟動了一些原型功能:

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

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

我還初始化了一個對象:

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

我的意思是我可以使用book.someFunction()但我只是好奇是否有辦法正確訪問頂級對象。 對不起,如果這是一個愚蠢的問題,我會嘗試澄清任何不清楚的事情。 謝謝

不,不是自動的。 也就是說,你必須告訴子對象頂級對象是什么,所以在bookinit函數中,你會得到這樣的東西:

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

我可能在這里做了一些假設,但這可能與你在訪問實例化的書方面所尋求的一致。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM