gpt4 book ai didi

javascript - 命名空间外部 Javascript 无法从目标 javascript 访问

转载 作者:行者123 更新时间:2023-12-02 19:56:52 25 4
gpt4 key购买 nike

我有我的 JavaScript 文件:

foo.js

var FooNS = {
T:5,
S: FooNS.T+5, //ERROR1
doSomething : function(adder)
{
//Do Something here.
}
};

这是我的另一个js文件:

useFoo.js

$(document).ready(function()
{
FooNS.doSomething(5); //ERROR2
});

这是我在包含 js 的页面上发现的两个 Javascript 错误(通过 Chrome Inspector):

  • ERROR1 -> 未捕获类型错误:无法读取未定义的属性“T”(foo.js)
  • ERROR2 -> 未捕获类型错误:无法调用未定义的方法“doSomething”(在 useFoo.js 中)

我无法找出这些错误的原因/命名空间的正确使用。有什么建议吗?

最佳答案

T 不作为全局变量存在,这就是您尝试使用它的方式。

var FooNS = {
T:5,
S: T+5, // <-- here you are trying to access the global variable T
doSomething : function(adder)
{
//Do Something here.
}
};

您正在寻找的内容可能与此类似:

var FooNS = {
T:5,
doSomething : function(adder)
{
//Do Something here.
}
};

FooNS.S = FooNS.T+5;

第二个错误是因为第一个错误导致 FooNS 从未被创建为对象,因此 FooNS 未定义。

关于javascript - 命名空间外部 Javascript 无法从目标 javascript 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485274/

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