繁体   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