我正在摆弄对象和方法,我有一个非常简单的示例,我用它来测试:
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
elements with ansrc
attribute specified should not have a script embedded within its tags.
您需要两个单独的 script
标记,一个用于导入外部脚本,另一个用于调用函数,例如:
<script src="test.js"></script>
<script>
shout.hello("World");
</script>
关于Javascript 外部对象全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419920/