2015-05-28 71 views
1
(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)声明的目的。这条线是做什么的,为什么它是必要的?使用.call继承原型(this)

回答

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

+0

那么,这是否意味着一次LoggerBase.call(本);在BookAppLogger函数中调用时,属性fname,lname和fullname是否添加到BookAppLogger对象中?可以在BookAppLogger.prototype中找到这些属性还是只能在BookAppLogger对象中找到这些属性? – mikelee54

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); 
0

不是一个真正的答案,但我想我会分享的ES6等同于上面的代码。这可能会让事情看起来更清楚。

class BookAppLogger extends LoggerBase { // BookAppLogger.prototype = Object.create(LoggerBase.prototype ... 
    constructor() { 
    super();        // LoggerBase.call(this); 
    } 
    logBook(book) {       // this.logBook = function(book) { ... 
    console.log('Book:', book.title); 
    } 
} 

然而,我们定义为constructor默认行为,所以我们就可以忽略它完全

// does the same thing! 
class BookAppLogger extends LoggerBase { 
    logBook(book) { 
    console.log('Book:', book.title); 
    } 
}