我正在尝试学习 JavaScript 对象继承。我指的是 Shelley Powers 的 JavaScript Cookbook。
在子类中你需要调用 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());