Reputation: 29
(function() {
LoggerBase.prototype.output = function(message) {
console.log('LoggerBase: ' + message);
};
function BookAppLogger() {
LoggerBase.call(this);
this.logBook = function(book) {
console.log('Book: ' + book.title);
}
}
BookAppLogger.prototype = Object.create(LoggerBase.prototype);
}());
In this code the BookAppLogger inherits the prototypes of the LoggerBase object, I think that is clear from the last statement. What I don't understand is the purpose of the LoggerBase.call(this)
statement. What does this line do and why is it neccessary?
Upvotes: 1
Views: 46
Reputation: 3451
Its just calling the base class constructor
LoggerBase
is a function object and the call method of a function can be used to call that function with a specific this
value. Calling LoggerBase
directly would result in this
being the global object, which in a browser is the window object.
function LoggerBase() {
console.log(this);
}
function BookAppLogger() {
LoggerBase.call(this); // will print the book logger
LoggerBase(); // will print the global object
}
BookAppLogger.prototype = Object.create(LoggerBase.prototype);
Upvotes: 0
Reputation: 556
BookAppLogger.prototype = Object.create(LoggerBase.prototype);
will only add LoggerBase.prototype
functions to BookAppLogger.prototype
but you cannot inherit the functions/properties that are written inside LoggerBase
function. For example if LoggerBase
is something like
function LoggerBase () {
this.fname = "First";
this.lname = "Last";
this.fullname = function(){
return this.fname + " " + this.lname;
}
}
LoggerBase.prototype.somefunction = function(){}
If you do not write LoggerBase.call(this)
inside BookAppLogger
, then only only LoggerBase somefunction
is inherited but not fname, lname, fullname
Upvotes: 1