2017-02-11 44 views
0

我是javascript的新用戶。我想通過使用print方法爲具有標題,作者和長度屬性的書寫一個構造函數。我嘗試了以下,我知道它不工作。請幫助!Thx!如何寫一個書寫構造函數並打印所有屬性而不使用Javascript中的CLASS函數?

這裏是我試圖代碼:

function Book(title,author,page){ 
    this.title = title; 
    this.author = author; 
    this.page = page 
    this.toString = toString 
} 

function toString(){ 
    return this.title + 'by' + this.author + ', is '+ this.page + ' long.' 
} 
print(){ 
    console.log(this.toString()); 
} 

var mobyDick = new Book ('Hamlet' , 'William Shakespeare' , 82); 
Hamlet.print(); 
+0

什麼是「哈姆雷特」應該指的是什麼?你爲什麼要'印刷'和'toSring'? 'console.log(mobyDick.toString())'會工作得很好。 –

回答

1

您可能希望將方法添加到原型,以便方法是通過Book所有「實例」共享。

function Book(title,author,page){ 
    this.title = title; 
    this.author = author; 
    this.page = page 
} 

Book.prototype.toString = function(){ 
    return this.title + 'by' + this.author + ', is '+ this.page + ' long.' 
} 
Book.prototype.print = function(){ 
    console.log(this.toString()); 
} 

var mobyDick = new Book ('Hamlet' , 'William Shakespeare' , 82); 

mobyDick.print() 

如果您要開始使用,我可以與您聯繫的最佳資源是您不瞭解JavaScript。 在這裏,你有一個link

希望你覺得它很有用。乾杯!

+0

謝謝@Carlos!我會檢查出來的。 –

相關問題