2011-09-21 14 views
0

好吧,這可能是一個愚蠢的問題,但我仍然在我的道路上學習面向對象JavaScript像一個職業,所以請不要笑,如果這個問題有點愚蠢......好吧,說我有這樣的一個簡單的Javascript寫法

var myObject = { 

    write:function(){ 
     return 'this is a string'; 

    } 
} 

一個非常簡單的對象,現在如果添加以下我的對象之外(請注意我有適當的股利在我的網頁):

document.getElementById('myDiv').innerHTML = myObject.write(); 

我的div的innerHTML是用字符串'this is a string'填充,但是如果我只是將以下內容添加到我的腳本(對象外部):myObject.write()

什麼都沒有退貨?有人可以告訴我爲什麼以及如何寫入頁面(不使用document.write(myObject.write()))將字符串輸出到頁面。如果這不能做到,請讓我知道爲什麼...

對不起,如果這是一個非常簡單/愚蠢的問題,但我正在學習。

下面是完整的東西,以幫助...

<html> 
<head> 
</head> 

<body> 

<div id='myDiv'></div> 

<script type="text/javascript"> 

var myObject = { 

    write:function(){ 
     return 'this is a string 2'; 

    } 
} 

//document.getElementById('myDiv').innerHTML = myObject.write(); 
myObject.write(); 

</script> 

</body> 
</html> 

回答

4

調用myObject.write()返回值。由於您沒有捕獲並處理返回值,因此沒有任何反應。

另一種方法將內容寫入文檔:

<body> 
<script>document.write(myObject.write())</script> 
...</body> <!--document.write ONLY works as desired when the document loads. 
     When you call document.write() after the document has finished initiating, 
     nothing will happen, or the page unloads--> 
+0

明智的答案 - 謝謝! –

+0

@Mark - 哈哈,這是真的,沒有意識到你想要這樣一個簡單的答案^ _^ – Neal

+0

嘿!我說沒有document.write,不要讓我標記你的答案Rob L,LOL!謝謝Neal –

0
var myObject = { 
    obj: (function(){ return document.getElementById('myDiv');})(), 
     //^^set object to write to 
    write:function(str){ 
     this.obj.innerHTML += str; 
     //^^add the string to this object 
    } 
} 

myObject.write('hello there'); 

演示:http://jsfiddle.net/maniator/k3Ma5/

+0

什麼是這裏的自我調用函數的目的是什麼? – pimvdb

+0

@pimvdb立即得到對象 – Neal