Plankje
Plankje

Reputation: 298

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?

Upvotes: 1

Views: 768

Answers (1)

Jacob
Jacob

Reputation: 78860

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.

Upvotes: 3

Related Questions