DIV CSS 佈局教程網

JavaScript toString() 與 toSource() 方法解析
編輯:JavaScript綜合知識     

toString() 的用途

toString() 會傳回物件的字串表示形式。對自訂物件而言,預設可能會得到類似 [object Object] 的結果,因此常需要依需求覆寫。

toSource() 的非標準特性

toSource() 並非標準方法,部分瀏覽器不支援。它通常用來取得物件的原始碼字串,不建議在正式專案中依賴。

範例

function book(title, publisher, price) {
  this.title = title;
  this.publisher = publisher;
  this.price = price;
}

const newBook = new book('Perl', 'Leo Inc', 200);

console.log(newBook.toString());
console.log(typeof newBook.toSource === 'function' ? newBook.toSource() : '不支援 toSource');

若需要自訂字串輸出,可為物件建立自己的 toString 方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved