Javascript 如何在嵌套结构中声明变量?
假设我有一个嵌套结构,其中包含JavaScript中的对象和函数,如下所示:Javascript 如何在嵌套结构中声明变量?,javascript,Javascript,假设我有一个嵌套结构,其中包含JavaScript中的对象和函数,如下所示: this.x = { f1: function() { }, f2: function() { }, nested: { f3: function() { }, f4: function() { } } } 假设我想要声明一个只有函数f3和f4知道的变量。在哪里以及如何声明此变量?您可以这样做吗 this.x = { f1: f
this.x = {
f1: function() {
},
f2: function() {
},
nested: {
f3: function() {
},
f4: function() {
}
}
}
假设我想要声明一个只有函数f3和f4知道的变量。在哪里以及如何声明此变量?您可以这样做吗
this.x = {
f1: function() {
},
f2: function() {
},
nested: (function() {
var nested_var;
return {
f3: function() {
// nested_var in scope here
},
f4: function() {
// and here, shared between f3 and f4
}
};
})();
}
只需在函数的作用域内声明变量,它将仅对该函数可见。前
function f3() {
var nestedVar = 3;
}
var notNested = nestedVar; // this will not work
从你的结构来看,嵌套应该是一个对象,对吗?您可以使用所谓的自执行函数
x = {
f1: function() {
//Does not have access to abc
},
f2: function() {
//Does not have access to abc
}
};
x.nested = (function() {
var abc = '123';
//Must return an object here to keep nested as an object
return {
f3: function() {
console.log(abc);
},
f4: function() {
console.log(abc);
}
};
})();
嵌套的
x.nested
中包含的函数将能够访问abc
,就好像它是一个彼此共享的全局变量,而f1
和f2
将不能访问一样。可能类似这样:
this.x = {
f1: function() {
},
f2: function() {
},
nested: (function(){
var priv=0;
return {
f3:function(){priv++;},
f4:function(){return priv;}
};
})()
};
(function(){/*code*/})(
部分是一个匿名函数,然后执行(您有时会在userscripts和bookmarklet中看到这些函数)。我想您想立即调用嵌套的?