![](/img/trans.png)
[英]Javascript namespacing - how to export functions and variables defined within a function scope based on their naming?
[英]scope of javascript variables within functions within function
有人可以解釋以下代碼嗎? 為什么內部函數不訪問同一父函數中的“內部”變量-但它們似乎與對等函數共享同一變量? 我知道我可以在子函數中使用“ this”來訪問父函數中的“ inside”變量,但是我對為什么需要此變量感到困惑。可能想要更靜態的東西? 我一直在使用這種模式來包裝javascript功能,但是現在我想知道是否有更好/更輕松的模式可以避免這種變量封裝的挑戰(更靜態)。 感謝您的見解。
var wrap = function() { var inside = null; function showInside() { console.log(inside); } function changeInside() { console.log(inside); inside += 'test'; } return { inside: inside, showInside: showInside, changeInside: changeInside }; }(); wrap.changeInside(); wrap.showInside(); wrap.changeInside(); wrap.showInside(); console.log(wrap.inside);
為什么內部函數不訪問同一父函數中的“內部”變量-但它們似乎與對等函數共享同一變量?
他們是這樣。
您感到困惑是因為當您說:
return {
inside:inside,
您復制的變量值 inside
的財產inside
的新對象。 您在創建對象時執行此操作。
以后更改變量的值時,它與屬性沒有關聯,因此該屬性不會更新。
您將需要使用getter / setters將屬性鏈接到變量。
var wrap = function() { var inside = null; function showInside() { console.log(inside); }; function changeInside() { console.log(inside); inside += 'test'; } return { get inside() { return inside; }, set inside(value) { inside = value; }, showInside: showInside, changeInside: changeInside }; }(); wrap.changeInside(); wrap.showInside(); wrap.changeInside(); wrap.showInside(); console.log(wrap.inside);
我認為您有一個概念上的問題。 讓我們看看:
var wrap = function(){
...
}();
那里的last ()
意味着您沒有分配要wrap
的函數,而是在調用該函數並將其返回值分配給wrap
。
返回值為
return {
inside:inside, //The value of inside (null)
showInside:showInside, //The local function showInside
changeInside:changeInside //The local function changeInside
};
看,您在wrap.inside
沒有變量inside
在調用函數時只有值。
首先,您可能需要執行以下操作:
var wrap = function() {
....
return this; //Return the object itself
}();
然后,函數內部的變量和函數屬於函數的作用域。 無法從該范圍之外訪問。 因此,您可以改為定義屬性 。
var wrap = function() {
this.inside = 1; //property
var insideVar = 2; //variable
this.showInside=function() { //property (with a function assigned to it)
console.log(insideVar);
console.log(this.inside);
};
this.changeInside=function() { //property
insideVar+=2;
this.inside+=1;
};
return this;
}();
現在:
console.log(wrap.inside); //-> 1
console.log(wrap.insideVar); //-> undefined
console.log(wrap.changeInside());
console.log(wrap.showInside); //-> 4 and 2
console.log(wrap.inside); //-> 2
希望區別是顯而易見的。 否則,請要求更多解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.