JavaScriptオブジェクトの継承を学ぼうとしています。シェリーパワーズのJavaScriptクックブックを参照しています。
サブクラスでは、そのプロパティを使用するためにsuperclass.apply(this、arguments)を呼び出す必要があります。そして本によると、私はsubclass.prototype = new superclass();のようなものも書く必要があります。
ただし、subclass.prototype = new superclass();を使用しなくても機能することに注意しました。声明。以下は私のコードです。subclass.prototype = new superclass();の目的は何ですか。
var Book = function (newTitle, newAuthor) {
var title;
var author;
title = newTitle;
author = newAuthor;
this.getTitle = function () {
return title;
}
this.getAuthor = function () {
return author;
}
};
var TechBook = function (newTitle, newAuthor, newPublisher) {
var publisher = newPublisher;
this.getPublisher = function () {
return publisher;
}
Book.apply(this, arguments);
this.getAllProperties = function () {
return this.getTitle() + ", " + this.getAuthor() + ", " + this.getPublisher();
}
}
//TechBook.prototype = new Book(); // Even when commented,
var b1 = new TechBook("C Pro", "Alice", "ABC Publishing");
var b2 = new TechBook("D Pro", "Bob", "DEF Publishing");
alert(b1.getAllProperties());
alert(b2.getAllProperties());
alert(b1.getTitle());
alert(b2.getTitle());