简体   繁体   中英

JavaScript: Create subclass from inside superclass instance

I am quite experienced with coding in Javascript, but there's still one thing I can't really wrap my head around.

I have a superclass, let's say Category. Now I want to create some instances of a subclass, let's say Post, from inside the Category instance. I want Post to have its own properties, but it also needs to be able to access properties of its parent. So this is the concept:

/* Superclass */
function Category(catID) {
    this.catID = catID;
    this.posts = [];

    this.addPost = function(id, content) {
        var post = new Post(id, content);

        post.prototype = Category;

        this.posts.push(post);
    }

    this.getPosts = function() {
        for(post in this.posts){
            this.posts[post].getContent();
        }
    }
}

/* Subclass */
function Post(postID, content) {
    this.postID = postID;
    this.content = content;

    this.getContent = function() {
        console.log('Post: '+ this.postID);
        console.log('Category: ' + this.catID);
        console.log('Content: ' + this.content);
    }
}

var cat1 = new Category(1); 
var cat2 = new Category(2);

cat1.addPost(101, 'First post in first category');
cat1.addPost(102, 'Second post in first category');
cat2.addPost(201, 'First post in second category');
cat2.addPost(202, 'Second post in second category');

cat1.getPosts();
cat2.getPosts();

I got stuck on the line post.prototype = Category . I would expect that now Post inherits the properties of Category , but it doesn't happen.

Can someone please help me out with this?

JavaScript does not have classes. The prototype of an object is another object . If you change your prototype assignment to this, it should work:

post.prototype = this;

I don't think this is what you want to do, however. An inheritance relationship does not make sense in this case. A Post is not really a type of Category . IMO, I would use composition instead of inheritance:

post.category = this;

That way, from your post, you should be able to access the members of the category through the category member .

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