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() 等標準工具來達到類似目的。