Is it possible to use inheritance in JavaScript only with the apply function and without using the prototype property?

I am trying to learn the inheritance of JavaScript objects. I mean JavaScript Cookbook by Shelley Powers.

In a subclass, you need to call superclass.apply (this, arguments) to use its properties. And according to the book, I also need to write something like subclass.prototype = new superclass ();

However, I noticed that everything works without using subclass.prototype = new superclass (); expression. Below is my code. What is the purpose of 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());
+3
source share
2 answers

, Book this. , , Book apply, .

TechBook , Book .

. - :

Book.prototype.getTitle = function()...

TechBook , TechBook.


, . , , .

+4

JavaScript . JavaScript Cookbook by Shelley Powers.

superclass.apply(, ) . - subclass.prototype = ();

. Javascript , , . , .

, , .

Book TechBook, , this TechBook, .

, new TechBook, TechBook.prototype, .

, .

, Book TechBook , .

+1

All Articles