(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);
}());
在这段代码中,BookAppLogger继承了LoggerBase对象的原型,我认为从上一条语句可以清楚地看出这一点。我不理解
LoggerBase.call(this)
语句的目的。这条线有什么作用,为什么必要? 最佳答案
BookAppLogger.prototype = Object.create(LoggerBase.prototype);
只会将
LoggerBase.prototype
函数添加到BookAppLogger.prototype
,但是您不能继承LoggerBase
函数内部编写的函数/属性。例如,如果LoggerBase
类似于function LoggerBase () {
this.fname = "First";
this.lname = "Last";
this.fullname = function(){
return this.fname + " " + this.lname;
}
}
LoggerBase.prototype.somefunction = function(){}
如果您未在
LoggerBase.call(this)
内编写BookAppLogger
,则仅继承LoggerBase somefunction
,而不继承fname, lname, fullname