DIV CSS 佈局教程網

深入認識 JavaScript 的 Boolean.toSource() 方法
編輯:JavaScript基礎知識     

Boolean.toSource() 是一個用來取得物件原始程式碼字串的方法。透過它,你可以把一個物件「還原」成一段描述其內容的程式碼。

需要特別留意的是,此方法在 Internet Explorer 中無法使用,主要見於 Firefox 等瀏覽器。

語法

boolean.toSource()

無參數。

回傳值

回傳代表該物件的原始程式碼字串。

實作範例

<html>
<head>
<title>JavaScript toSource() Method</title>
</head>
<body>
<script type="text/javascript">
function book(title, publisher, price) {
  this.title = title;
  this.publisher = publisher;
  this.price = price;
}
var newBook = new book("Perl","Leo Inc",200);
document.write(newBook.toSource());
</script>
</body>
</html>

執行後的結果如下:

({title:"Perl", publisher:"Leo Inc", price:200})

透過這個範例,我們可以清楚看到 toSource() 如何將 book 物件的屬性與值輸出成一段物件字面值。由於它並非標準方法,正式開發中通常會改用 JSON.stringify() 等標準工具來達到類似目的。

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