所以我想知道是否可以從範圍外訪問一個變量(它有一個函數的值)。我有這樣的代碼:函數內的javascript函數
function parentFunction(){
var childFunction = function() {
// do something
}
}
$(function(){
// need to access childFunction() here.
});
所以我想知道是否可以從範圍外訪問一個變量(它有一個函數的值)。我有這樣的代碼:函數內的javascript函數
function parentFunction(){
var childFunction = function() {
// do something
}
}
$(function(){
// need to access childFunction() here.
});
var childFunction;
function parentFunction(){
childFunction = function() {
// do something
}
}
$(function(){
childFunction();
});
我想,如果childFunction捕獲parentFunction中的任何閉包,這很有用,但否則會失去命名空間並污染全局命名空間。 – Matt
假設這是發生在全球所有在一起,我只是說明範圍... – jondavidjohn
它的工作 - 我只需要調用parentFunction首先初始化childFunction的值。然後我可以打電話給兒童功能。謝謝。 – donkapone
不,你不知道。實現這一目標的唯一方法是使所需childFunction parentFunction的屬性:
var parentFunction = (function(){
var actualParentFunction = function(){
this.childFunction = function() {
// do something
};
}
return new actualParentFunction();
})();
在這一點上,你可以這樣做:
parentFunction.childFunction();
可以'parentFunction()'返回'childFunction ()'變量在它的執行結束?或者你在調用'parentFunction()'之前試圖影響'childFunction()'? – Rodaine