2015-02-09 44 views
0

我瞎搞的對象和方法,我有我使用來測試這個非常簡單的例子:Javascript外部對象全球?

var shout = { 
 
    hello: function(variable){ 
 
    console.log("Hello " + variable); 
 
    } 
 
}; 
 

 
shout.hello("World");

這工作得很好。但是,如果我把對象shout在外部文件中,然後運行shout.hello("world");我得到什麼:

//external file: test.js 
 
var shout = { 
 
    hello: function(variable){ 
 
    console.log("Hello " + variable); 
 
    } 
 
};

<!-- my html document --> 
 
<script src="test.js"> 
 
shout.hello("World"); 
 
</script>

我在做什麼錯?

回答

3

MDN

script元素與規定不應該有它的嵌入標籤中的腳本的src屬性。

你需要兩個獨立的script標籤,一個以導入外部腳本,另一個調用的函數,例如:

<script src="test.js"></script> 
<script> 
shout.hello("World"); 
</script> 
2

您需要兩個單獨的script標記,忽略標記src attribute的內容。

<script src="test.js"></script> 
<script> 
    shout.hello("World"); 
</script> 
+0

我會接受這個答案的原因是第一次,它作品。 你能解釋一下這個原因嗎?編輯:嘿!我不知道這個 :) – 2015-02-09 21:44:33