Javascript外部对象全球?
问题描述:
我瞎搞的对象和方法,我有我使用来测试这个非常简单的例子: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>
我在做什么错?
答
从MDN:
script
元素与规定不应该有它的嵌入标签中的脚本的src
属性。
你需要两个独立的script
标签,一个以导入外部脚本,另一个调用的函数,例如:
<script src="test.js"></script>
<script>
shout.hello("World");
</script>
答
您需要两个单独的script
标记,忽略标记src
attribute的内容。
<script src="test.js"></script>
<script>
shout.hello("World");
</script>
我会接受这个答案的原因是第一次,它作品。 你能解释一下这个原因吗?编辑:嘿!我不知道这个 :) – 2015-02-09 21:44:33