Javascript 外部对象全局?

标签 javascript object scope

我正在摆弄对象和方法,我有一个非常简单的示例,我用它来测试:

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 an src 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/

相关文章:

javascript - 自动完成从数据库输出两个字段

javascript - 无法在不同域上设置 cookie

c++ - JUCE:无法实例化类 "operate ' =' does not match the operands"

javascript - 如何遍历对象数组并制作键值对?

javascript - 将对象数组更改为 CSV 模式

javascript - 在函数内部调用函数 - 问题 :function not executing

javascript - 默认情况下,Vuetify 为所有 v-text-field 设置概述

javascript - 在 javaScript 中使用 onclick() 调用 2 个不同的 div

javascript - 变量的范围

objective-c - 从 subview Controller 设置父 View Controller 类的属性值?