[英]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. 我对Java编码非常有经验,但是还有一件事我无法真正解决。
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.
现在,我想从Category实例内部创建一个子类的实例,比如说Post。 I want Post to have its own properties, but it also needs to be able to access properties of its parent.
我希望Post具有自己的属性,但还需要能够访问其父级的属性。 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
. 我陷入了
post.prototype = Category
的行。 I would expect that now Post
inherits the properties of Category
, but it doesn't happen. 我希望现在
Post
继承了Category
的属性,但它不会发生。
Can someone please help me out with this? 有人可以帮我解决这个问题吗?
JavaScript does not have classes. JavaScript没有类。 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
. Post
并不是Category
。 IMO, I would use composition instead of inheritance: IMO,我将使用合成代替继承:
post.category = this;
That way, from your post, you should be able to access the members of the category through the category member . 这样,从您的帖子中,您应该能够通过类别成员访问该类别的成员 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.