JavaScript 的 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 物件的內容還原成一段可供閱讀的物件字面值。由於相容性的限制,實際專案開發時較少使用,但作為除錯與理解物件結構的工具仍具有一定價值。