简体   繁体   English

如何从其中的另一个对象访问原型对象

[英]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() ; 我有一个主要对象,通过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. 我的意思是我可以使用book.someFunction()但我只是好奇是否有办法正确访问顶级对象。 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: 也就是说,你必须告诉子对象顶级对象是什么,所以在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;
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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