JavaScript:从超类实例内部创建子类

JavaScript:从超类实例内部创建子类,javascript,inheritance,object,subclass,superclass,Javascript,Inheritance,Object,Subclass,Superclass,我对用Javascript编写代码很有经验,但还有一件事我不能完全理解 我有一个超类,比如说类别。现在我想从Category实例内部创建子类的一些实例,比如Post。我希望Post有自己的属性,但它也需要能够访问其父级的属性。这就是概念: /* Superclass */ function Category(catID) { this.catID = catID; this.posts = []; this.addPost = function(id, content)

我对用Javascript编写代码很有经验,但还有一件事我不能完全理解

我有一个超类,比如说类别。现在我想从Category实例内部创建子类的一些实例,比如Post。我希望Post有自己的属性,但它也需要能够访问其父级的属性。这就是概念:

/* 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();
我被卡在线路上了。prototype=Category。我希望现在
Post
继承了
Category
的属性,但这并没有发生


有人能帮我解决这个问题吗?

JavaScript没有类。一个对象的原型是另一个对象。如果您将原型任务更改为此,它应该可以工作:

post.prototype = this;
然而,我不认为这是你想要做的。在这种情况下,继承关系没有意义。
Post
实际上不是一种
类别
。在我看来,我会使用组合而不是继承:

post.category = this;

这样,从您的帖子中,您应该能够通过类别成员访问该类别的成员。

感谢您的快速回复!不幸的是,在这种情况下使用
不起作用。+1。英雄所见略同。你的答案和我的一样,但你几秒钟前就得到了。我将删除我的答案。非常感谢。关于
Post
不应该与
Category
有继承关系这一事实,您是绝对正确的。组合范式工作得非常完美。