使用.call继承原型(this)

时间:2015-05-28 08:04:07

标签: javascript prototype

(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)陈述的目的。这条线做了什么,为什么有必要呢?

2 个答案:

答案 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);