(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)
陈述的目的。这条线做了什么,为什么有必要呢?
答案 0 :(得分:1)
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
答案 1 :(得分:0)
它只是调用基类构造函数
LoggerBase
是一个函数对象,函数的call method可用于调用具有特定this
值的函数。直接调用LoggerBase
会导致this
成为全局对象,在浏览器中它是窗口对象。
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);