gpt4 book ai didi

javascript - 无法访问另一个javascript文件中的变量

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:05 24 4
gpt4 key购买 nike

所以我已经将需要的每个文件链接到 index.html 文件中:

    <script src="jquery.js"></script>
<script src="notify.js"></script>
<script src="script.js"></script>

我在“notify.js”中创建了一个对象:

    var notify = {
newNotification : function(text) {
}
}

脚本.js :

alert(notify.newNotification);

当我尝试访问“script.js”中的“通知”对象时,它工作得很好。但我想使用 jquery,所以我将 $(document).ready() 添加到两个文件中,如下所示:

通知.js

    $(document).ready (
function() {
var notify = {
newNotification : function(text) {
}
}
}
)

脚本.js:

    $(document).ready (
function() {
alert(notify.newNotification);
}
)

在我添加之后,它出现了 notify is not defined。怎么了?谁能解释为什么它不起作用?

最佳答案

正如您在 $(document).ready( 中的 notify.js 中定义的 var notify ,这是一个匿名函数和 var notify范围仅限于此功能。

所以它在$(document).ready(函数之外是不可访问的

要使外部可访问,请不要将其包装在 $(document).ready( 函数

像这样:-

var notify;
$(document).ready(function () {
notify = {
newNotification: function (text) { }
}
});

关于javascript - 无法访问另一个javascript文件中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com