我有一个“主机”javascript闭包,其中我保留了我在网站上使用的所有常见变量
var hostFunction = (function () {
var variableA = $("#variableA");
var variableB = $("#variableB");
// some usefull code here
} ());
在我的网站上,在另一个javascript文件中,我有另一个关闭
var childFunction = (function () {
var changeValue = function () {
variableA.html("I was changed");
};
// other usefull code
} ());
如何在“hostFunction”中插入“childFunction”,以便我可以访问这些变量?
在网站上共享变量的最佳做法是什么,但是将它们保留在范围内以便它们不与其他javascript变量冲突?
答案 0 :(得分:2)
如果需要全局共享任何信息,最佳做法是使用命名空间来降低变量与其他变量冲突的风险。
This blog post在javascript中给出了命名空间的合理介绍。
答案 1 :(得分:0)
我认为您需要单词this
才能在其他范围中看到这些变量
var hostFunction = (function () {
this.variableA = $("#variableA");
this.variableB = $("#variableB");
// some usefull code here
} ());
您在childFunction的构造函数中传递主机,如下所示:
var childFunction = (function (myHost) {
var changeValue = function () {
myHost.variableA.html("I was changed");
};
// other usefull code
} (hostFunction));